使用subprocess.Popen

时间:2018-12-19 13:33:35

标签: python-3.x unix process

我想使用包含多个带有subprocess.Popen管道的命令。这是我的简短剧本

#!/usr/bin/env python 

import subprocess
import datetime
import shlex

todayyearnumber = str(datetime.datetime.now().strftime('%Y'))

command = 'git log --grep "' + todayyearnumber + '.*commit" --oneline'
command2 = 'cut -d " " -f4'

argsplit=shlex.split(command)
argsplit2=shlex.split(command2)

process1=subprocess.Popen(argsplit, cwd=ebb_path, stdout=subprocess.PIPE)

process2=subprocess.Popen(argsplit2, stdin=process1.PIPE, stdout=subprocess.PIPE)

print(process2.stdout.read().decode('utf-8'))

但是,我收到错误消息

回溯(最近通话最近):   文件“ ./proces.py”,第35行,在     process2 = subprocess.Popen(argsplit2,stdin = process1.PIPE,stdout = subprocess.PIPE) AttributeError:“ Popen”对象没有属性“ PIPE”

你能帮我弄个错吗?

1 个答案:

答案 0 :(得分:0)

这是因为PIPE是定义为subprocess.PIPE的常量。

如果我对您的理解正确,那么完整的程序将如下所示:

#!/usr/bin/env python

import subprocess
import shlex

command = 'echo a b c'
command2 = "awk '{print $2}'"

argsplit=shlex.split(command)
argsplit2=shlex.split(command2)

ebb_path="/tmp/"
process1=subprocess.Popen(argsplit, cwd=ebb_path, stdout=subprocess.PIPE)
stdout_data, stderr_data = process1.communicate(timeout=1)

process2=subprocess.Popen(argsplit2, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
stdout_data2, _ = process2.communicate(input=stdout_data,
                                    timeout=1)

print(stdout_data2.decode('utf-8'))