2016-10-12 85 views
0

我正在使用subprocess.Popen執行make命令。但是當make失敗時,我並沒有從make中得到確切的錯誤,只是繼續運行。如何獲得腳本停止和顯示控制檯make命令將subprocess.Popen stderr重定向到控制檯

def app(self, build, soc, target): 
    command = "make BUILD=%s SOC=%s TARGET=%s" % (build, soc, target) 
    subprocess.Popen(command.split(), shell=False, 
           stdout=subprocess.PIPE, 
           stderr=subprocess.PIPE).communicate() 
+0

什麼(蟒蛇相關的)錯誤你得到,當它失敗了呢? –

+0

如果可能,最簡單的方法是使用Python 3.4,並用'subprocess.run()'將調用替換爲'subprocess.popen()'。它返回一個包含stdout和stderr的返回碼和結果作爲字符串列表的對象。 –

+0

@Tom Dalton其實問題是它只是繼續,並沒有拋出異常。然後在腳本中,它依賴於make命令傳遞,這裏是腳本失敗的時候。 – homeGrown

回答

2

的準確輸出,你可以嘗試更換:

subprocess.Popen(command.split(), shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 

有:

p = subprocess.Popen(command.split(), shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
print p.communicate() 
print p.returncode 

讓我們知道打印輸出的樣子。

0

如果您想讓make輸出真正進入控制檯,請不要使用subprocess.PIPE作爲stdout/stderr。默認情況下,被調用的進程將使用Python進程的stdout/stderr句柄。在這種情況下,你可以使用subprocess.check_call()功能提出一個subprocess.CalledProcessError如果被叫返回一個非零的退出代碼:

subprocess.check_call(command.split()) 

但是,如果您需要捕獲使用的化妝輸出在你的腳本,你可以使用類似subprocess.check_output()功能:

try: 
    output = subprocess.check_output(command.split(), stderr=subprocess.STDOUT) 
except subprocess.CalledProcessError as e: 
    output = e.output 
    # error handling here 

注意,這結合了輸出和錯誤輸出到一個單一的值。如果單獨需要的話,你就需要使用subprocess.Popen構造結合.communicate()方法和手動檢查returncode屬性Popen對象:

p = subprocess.Popen(command.split(), stdout=subprocess.PIPE, 
     stderr=subprocess.PIPE) 
out, err = p.communicate() 
if p.returncode != 0: 
    # raise exception or other error handling here 
相關問題