2010-03-26 133 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讀起來像一個普通的文件。