捕获子进程输出

sch*_*eck 25 python subprocess

我了解到在Python中执行命令时,我应该使用子进程.我想要实现的是通过ffmpeg编码文件并观察程序输出直到文件完成.Ffmpeg将进度记录到stderr.

如果我尝试这样的事情:

child = subprocess.Popen(command, shell=True, stderr=subprocess.PIPE)
complete = False
while not complete:
    stderr = child.communicate()

    # Get progress
    print "Progress here later"
    if child.poll() is not None:
        complete = True
    time.sleep(2)
Run Code Online (Sandbox Code Playgroud)

调用child.communicate()并等待命令完成后,程序不会继续.还有其他方法可以跟随输出吗?

Vla*_*ala 27

沟通()阻塞,直到子进程的回报,所以在循环线的其余部分将只得到执行后,子进程结束运行.从stderr读取也会阻塞,除非你逐字逐句阅读:

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()
Run Code Online (Sandbox Code Playgroud)

这将为您提供实时输出.从Nadia的答案采取这里.