1

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

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

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)

我哪里错了?

4

1 回答 1

3

这一行:

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

挂起,因为read()意味着“读取所有数据直到 EOF”。请参阅文档。看起来你可能想一次读一行:

print p.stdout.readline()
于 2013-06-17T11:39:38.740 回答