我正在从 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模板网!
如何将函数绑定到 Qt 菜单栏中的操作?How to bind a function to an Action from Qt menubar?(如何将函数绑定到 Qt 菜单栏中的操作?)
PyQt 启动后进度跃升至 100%PyQt progress jumps to 100% after it starts(PyQt 启动后进度跃升至 100%)
如何将 yaxis 刻度标签设置在固定位置,以便当我How to set yaxis tick label in a fixed position so that when i scroll left or right the yaxis tick label should be visible?(如何将 yaxis 刻度标签设
`QImage` 构造函数有未知关键字 `data``QImage` constructor has unknown keyword `data`(`QImage` 构造函数有未知关键字 `data`)
将 x 轴刻度更改为自定义字符串Change x-axis ticks to custom strings(将 x 轴刻度更改为自定义字符串)
如何在python中将文件保存为excel时显示进度条?How to show progress bar while saving file to excel in python?(如何在python中将文件保存为excel时显示进度条?)