2

这是我的代码。

import subprocess

bashCommand = "./program -s file_to_read.txt | ./awk_program.txt"
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output = process.communicate()[0]
output2 = process.stdout
print output
print output2

在终端中单独使用此 bash 命令时,会打印 awk_program 的输出(仅打印到标准输出)。但在 python 中,输出什么也不打印,而 output2 打印

<closed file '<fdopen>', mode 'rb' at 0x2b5b20>

我需要做什么才能返回输出?

4

1 回答 1

2

您需要使用该选项shell=TruePopen()使管道正常工作。

请注意,如果您不知道Popen输入的确切来源,则shell=True存在安全风险

此外,您不需要在bashCommand这里拆分。例如:

>>> import subprocess as sp    
>>> cmd = 'echo "test" | cat'
>>> process = sp.Popen(cmd,stdout=sp.PIPE,shell=True)
>>> output = process.communicate()[0]
>>> print output
test
于 2012-11-11T19:04:06.497 回答