处理stdin和stdout

时间:2013-06-17 11:31:23

标签: python subprocess stdout stdin pipe

我正在尝试使用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)

我哪里错了?

1 个答案:

答案 0 :(得分:3)

这一行:

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

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

print p.stdout.readline()
相关问题