捕获子进程输出 [英] Capture subprocess output

查看:53
本文介绍了捕获子进程输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I learned that when executing commands in Python, I should use subprocess. What I'm trying to achieve is to encode a file via ffmpeg and observe the program output until the file is done. Ffmpeg logs the progress to stderr.

如果我尝试这样的事情:

If I try something like this:

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)

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

the programm does not continue after calling child.communicate() and waits for the command to complete. Is there any other way to follow the output?

推荐答案

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.

这篇关于捕获子进程输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆