【问题标题】:Capture subprocess output [duplicate]捕获子进程输出[重复]
【发布时间】:2011-02-01 06:54:09
【问题描述】:

我了解到,在 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)

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

【问题讨论】:

    标签: python subprocess


    【解决方案1】:

    communicate() 阻塞直到子进程返回,因此循环中的其余行只会在子进程完成运行后执行。从 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()
    

    这将为您提供实时输出。摘自 Nadia 的回答 here

    【讨论】:

    【解决方案2】:

    .communicate() "从 stdout 和 stderr 读取数据,直到到达文件末尾。等待进程终止。"

    相反,您应该能够像普通文件一样从child.stderr 读取。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-21
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 2010-10-29
      • 2020-05-23
      • 2020-10-18
      • 1970-01-01
      相关资源
      最近更新 更多