2012-11-11 32 views
2

这是我的代码。Python子过程stdout和沟通()[0]不打印输出该终端将

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中,输出什么也没有打印,输出2打印

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

我需要做什么来返回输出?

回答

2

您需要使用Popen()中的选项shell=True才能使管道起作用。

请注意,如果您不确切知道Popen输入来自哪里,那么shell=Truesecurity risk

此外,您不需要在此处拆分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 
+0

这使得它给了一些程序的回应。但仍然不是在终端 – chimpsarehungry

+0

@chimpsarehungry中运行bashCommand的输出:也许进程输出到stderr以及? –

+1

也许,但添加stderr = subprocess.STDOUT或stderr = subprocess.PIPE没有帮助 – chimpsarehungry