且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

捕获子进程输出

更新时间:2022-06-22 04:23:28

communicate() 阻塞直到子进程返回,所以循环中的其余行只会在子进程之后执行进程已经运行完毕.从 stderr 读取也会阻塞,除非您像这样逐个读取:

communicate() blocks until the child process returns, so the rest of the lines in your loop will only get executed after the child process has finished running. Reading from stderr will block too, unless you read character by character like so:

import subprocess
import sys
child = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE)
while True:
    out = child.stderr.read(1)
    if out == '' and child.poll() != None:
        break
    if out != '':
        sys.stdout.write(out)
        sys.stdout.flush()

这将为您提供实时输出.摘自 Nadia 的回答此处.

This will provide you with real-time output. Taken from Nadia's answer here.