【问题标题】:Handling stdin and stdout处理标准输入和标准输出
【发布时间】:2013-06-13 08:16:19
【问题描述】:

我正在尝试使用subprocess 来处理流。我需要将数据写入流,并且能够异步从中读取(在程序终止之前,因为我的需要几分钟才能完成,但它会输出)。

对于学习案例,我一直在使用 Windows 7 中的 timeout 命令:

import subprocess
import time

args = ['timeout', '5']
p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False)
p.stdin.write('\n') # this is supposed to mimic Enter button pressed event.

while True:
    print p.stdout.read() # expected this to print output interactively. This actually hungs.
    time.sleep(1)

我哪里错了?

【问题讨论】:

    标签: python subprocess stdout stdin pipe


    【解决方案1】:

    这一行:

    print p.stdout.read() # expected this to print output interactively. This actually hungs.
    

    挂起,因为read() 的意思是“读取所有数据直到 EOF”。见the documentation。看起来你可能想一次读一行:

    print p.stdout.readline()
    

    【讨论】:

    • 它读取数据直到缓冲区的EOF。如果缓冲区变空,它不会挂起。
    • @iTayb 不,它会等到文件结束。对于管道文件结束是当输入生成进程关闭文件或终止时。 EOF 不会仅仅因为进程暂时停止写入而发生。尝试例如运行python -c "import sys; print sys.stdin.read()" 并查看是否仅反映您编写的第一行或您使用 Ctrl-Z/Ctrl-D/类似指示 EOF 后编写的每一行。