問題描述
我正在從 Python 運行一個 C 可執行文件,這個可執行文件有時會出現段錯誤.當它發生段錯誤時,子進程模塊不會在 stdout 或 stderr 中返回任何內容.
I'm running a C executable from Python and this executable sometimes segfaults. When it segfaults the subprocess module does not return anything in stdout or stderr.
示例代碼:
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
");
int x = 1 / 0;
}
./a.out
的輸出是:
hello world
Floating point exception
Python 代碼的輸出是(在 Linux 中,python 2.7):
The output of the Python code is (in Linux, python 2.7):
out: ""
err: ""
-8
有沒有辦法在可執行文件崩潰的情況下獲取它的輸出?
Is there a way to get the output of the executable even if it crashes?
將返回碼轉換為字符串消息的通用方法也不錯.
A generic method to translate returncode to a string message, would also be nice.
推薦答案
你的 C 程序沒有刷新它的輸出緩沖區.解決此問題的最簡單方法是將 STDOUT 的輸出模式更改為無緩沖:
Your C program is not flushing its output buffer. The easiest way around this problem is to change the output mode of STDOUT to unbuffered:
#include <stdio.h>
int main(int argc,char **argv) {
setvbuf(stdout,_IONBF,0,0);
printf("hello world
");
int x = 1 / 0;
}
現在您的程序(我對其進行了編輯以修復錯字)產生了正確的輸出:
Now your program (which I edited to fix a typo) produces the correct output:
$ python2.7 x.py
out: "hello world
"
err: ""
0
$
在我的 Mac 上返回碼是 0,令人困惑,因為因信號而終止的程序沒有返回碼.
The return code is 0 on my Mac, confusingly, because programs that are terminated for a signal don't have a return code.
這篇關于Python 子進程模塊在段錯誤時不返回標準輸出的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!