您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python-逐行读取子流程标准输出

Python-逐行读取子流程标准输出

自从我上一次使用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)。

python 2022/1/1 18:20:58 有503人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶