python - 检测进程中止

标签 python subprocess popen

我正在使用 subprocess.Popen 从 python 运行一些 C++ 二进制应用程序。我该如何处理该进程的中止?例如,我的 C++ 因断言而中断,我在控制台中看到:

binary: /usr/include/.../file.hpp:42: Assertion `min <= max' failed.
Aborted

进程关闭,但如何在 python 中使用 popen 句柄捕获它?

最佳答案

如果您已调用handle = subprocess.Popen(...),则必须在某个时刻调用handle.wait(). Its return value ,同时也是进程句柄对象的 returncode 属性,显示进程是否正常完成(值 >= 0)或者是否由于信号而终止(带有值 < 0)。

示例:

>>> import subprocess
>>> subprocess.call("kill -ABRT $$", shell=True)
-6
>>> a = subprocess.Popen("kill -ABRT $$", shell=True)
>>> a.wait()
-6
>>> subprocess.call("kill -SEGV $$", shell=True)
-11

C 程序看起来像

#include <assert.h>

int main() {
    assert(0);
}

我能做到

>>> import subprocess
>>> subprocess.call(["./ass"])
ass: ass.c:4: main: Assertion `0' failed.
-6

所以我有同样的效果。

关于python - 检测进程中止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11227164/

相关文章:

python - 计算列表列中两个元素的出现次数

python - 在 python 中使用 shell=True 清理子进程的输入

python - Popen子处理问题

python - wxpython中的对象对齐

python - Kubernetes 官方教程 : The web page at http://localhost:6000/might be temporarily down or it may have moved permanently to a new web address

python - 使用beautifulsoup时出现属性错误如何解决?

python - Python如何获取手册页内容?

python - subprocces.call 语法错误python

python : call ffmpeg command line with subprocess

python - 使用 Popen 和启动/等待在 python 中运行子进程时无法获取退出代码