Python subprocess.Popen 实时输出 stdout

大部分的程序是这样的:

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()

猜你喜欢

转载自blog.csdn.net/u012206617/article/details/84560895