【问题标题】:Python Subprocess stdout and communicate()[0] not printing output that terminal wouldPython Subprocess stdout 和communicate()[0] 不打印终端的输出
【发布时间】:2012-10-31 07:47:54
【问题描述】:

这是我的代码。

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>

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

【问题讨论】:

    标签: python terminal popen subprocess


    【解决方案1】:

    您需要在Popen() 中使用选项shell=True 才能使管道正常工作。

    请注意,如果您不知道Popen 输入的确切来源,那么shell=True 就是security 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
    

    【讨论】:

    • 这使它从程序中得到了一些响应。但仍然与在终端中运行该 bashCommand 的输出不同
    • @chimpsarehungry:也许进程也会输出到stderr?
    • 可能,但添加 stderr=subprocess.STDOUT 或 stderr=subprocess.PIPE 没有帮助
    • @chimpsarehungry 查看我的编辑。它是这样工作的吗? Pipes 和 subprocess 的工作方式与您预期的不太一样...
    • 谢谢。这是我的问题。不知道为什么我把它放在那里。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多