2013-10-02 37 views
2

我正在編寫一個腳本,它可以將文件名作爲輸入,編譯並運行它。爲python子進程創建的進程捕獲運行時錯誤

我將一個文件的名稱作爲輸入(input_file_name)。

self.process = subprocess.Popen(['gcc', input_file_name, '-o', 'auto_gen'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False) 

接下來,我使用的是相同的(POPEN)調用執行可執行文件:我第一次從蟒蛇內編譯文件

subprocess.Popen('./auto_gen', stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False) 

在這兩種情況下,我趕上了標準輸出(並使用

(output, _) = self.process.communicate() 

標準錯誤)的內容現在,如果編譯過程中出現錯誤,我能趕上錯誤,因爲返回碼是1,我可以得到錯誤的細節,因爲GCC並將它們發送標準錯誤。

但是,即使執行成功,程序本身也可以返回一個隨機值(因爲最後可能沒有「返回0」)。所以我無法使用返回碼捕獲運行時錯誤。此外,可執行文件不會在stderr上發送錯誤詳細信息。所以我不能使用我用來捕獲編譯時錯誤的技巧。

捕獲運行時錯誤或打印錯誤的詳細信息的最佳方法是什麼?也就是說,如果./auto_gen引發了分段錯誤,我應該能夠打印以下任一項:

'Runtime error' 
'Segmentation Fault' 
'Program threw a SIGSEGV' 

回答

0

試試這個。代碼運行失敗並打印到stderr的子進程。 except塊捕獲特定的錯誤退出代碼和stdout/stderr,並顯示它。

#!/usr/bin/env python 

import subprocess 

try: 
    out = subprocess.check_output(
     "ls non_existent_file", 
     stderr=subprocess.STDOUT, 
     shell=True) 
    print 'okay:',out 
except subprocess.CalledProcessError as exc: 
    print 'error: code={}, out="{}"'.format(
     exc.returncode, exc.output, 
     ) 

輸出示例:

$ python ./subproc.py 
error: code=2, out="ls: cannot access non_existent_file: No such file or directory 
" 
+0

OP表示由於沒有'return 0'(嘗試構建並運行'main(){}'C程序),子進程可能返回*任意*退出狀態,即不能使用'returncode! = 0'來檢測故障。子進程也不會將錯誤輸出到stderr(並且看起來好像是stdout),因此'exc.output'也沒有幫助。 – jfs

0

如果./autogen由信號殺死然後self.process.returncode.wait().communicate()後)小於零且其絕對值報告例如該信號,爲returncode == -11SIGSERV