我正在Python中運行C可執行文件,並且此可執行文件有時會出現段錯誤。當它發生段錯誤時,子進程模塊不會在stdout或stderr中返回任何內容。Python子流程模塊不會在段錯誤上返回stdout
樣品的編號:
import subprocess
proc = subprocess.Popen(['./a.out'], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate()
print 'out: "%s"' % out
print 'err: "%s"' % err
print proc.returncode
爲a.out
的來源是:
int main() {
printf("hello world\n");
int x = 1/0;
}
的./a.out
的輸出是:
hello world
Floating point exception
的Python代碼的輸出是(在Linux中,python 2.7):
out: ""
err: ""
-8
有沒有辦法獲得可執行文件的輸出,即使它崩潰?
將returncode轉換爲字符串消息的一般方法也很好。
好的解決方案,如果你控制C代碼,並且能夠將'setvbuf'調用加入並重新編譯。我假設修改第三方C代碼是不可能的。 – Celada
那麼,如果你的第三方代碼在它崩潰之前沒有刷新它的stdout,那麼你可以做的事情就不多了。 – vy32