美文网首页
Python subprocess.Popen 实时输出 std

Python subprocess.Popen 实时输出 std

作者: 书SHU | 来源:发表于2017-11-10 16:34 被阅读2587次

大部分的程序是这样的:

from subprocess import Popen, PIPE, STDOUT

p = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=True)
while True:
    print(p.stdout.readline())
    if not line: 
        break

但是由于子程序没有进行 flush 的话,会把结果缓存到系统中。导致程序运行完成,上面的程序才会进行打出(会一直卡在readline这个函数)。

解决方法:

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)
for line in iter(p.stdout.readline, b''):
    print line,
p.stdout.close()
p.wait()

相关文章

网友评论

      本文标题:Python subprocess.Popen 实时输出 std

      本文链接:https://www.haomeiwen.com/subject/oeobmxtx.html