2010-03-26 136 views
24

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

的PROGRAMM不会继续调用child.communicate后(),并等待命令完成。有没有其他的方式来跟踪输出?

+0

相关:[Python:从subprocess.communicate()读取流输入)(http://stackoverflow.com/q/2715847/4279) – jfs 2015-06-13 13:54:05

回答

26

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

+0

我没有看到这个答案 - 我的问题是重复的。谢谢。 – schneck 2010-03-26 17:56:13

+3

在这个脚本中,'complete'变量没有用处。 – 2013-03-08 01:47:01

+0

@JaoaoMilasch编辑,谢谢! – 2013-04-19 22:09:11

1

.communicate()“宣读了输出和错误数据,直至到达档案结尾。等待进程终止。”

相反,你应该能够刚从child.stderr读起来像一个普通的文件。