自从我上一次使用Python以来已经很长时间了,但是我认为问题出在语句for line in proc.stdout
,该语句在遍历整个输入之前先读取整个输入。解决方案是改为使用readline()
:
#filters output
import subprocess
proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)
while True:
line = proc.stdout.readline()
if not line:
break
#the real code does filtering here
print "test:", line.rstrip()
当然,您仍然必须处理子进程的缓冲。
注意:根据文档,使用迭代器的解决方案应该与使用等效readline()
,除了预读缓冲区外,但是(或正因为如此)建议的更改确实为我带来了不同的结果(Windows XP上为Python 2.5)。