代码之家  ›  专栏  ›  技术社区  ›  schneck

捕获子进程输出[重复]

  •  24
  • schneck  · 技术社区  · 16 年前

    这个问题已经有了答案:

    我了解到在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.communication()并等待命令完成后,程序将不继续。是否有其他方法跟踪输出?

    2 回复  |  直到 11 年前
        1
  •  26
  •   Community Mohan Dere    9 年前

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

    这将为您提供实时输出。摘自娜迪亚的回答 here .

        2
  •  1
  •   ephemient    16 年前

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

    相反,你应该能够从 child.stderr 像普通的档案。