如何防止嵌入式python退出()我的进程

Car*_*cio 9 python embedded exception exit

我在运行嵌入式python时遇到了麻烦.事实证明,我无法捕获sys.exit()引发的SystemExit异常;

这是我到目前为止:

$ cat call.c 
#include <Python.h>
int main(int argc, char *argv[])
{
    Py_InitializeEx(0);
    PySys_SetArgv(argc-1, argv+1);
    if (PyRun_AnyFileEx(fopen(argv[1], "r"), argv[1], 1) != 0) {
        PyObject *exc = PyErr_Occurred();
        printf("terminated by %s\n",
                PyErr_GivenExceptionMatches(exc, PyExc_SystemExit) ?
                "exit()" : "exception");
    }
    Py_Finalize();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

另外,我的脚本是:

$ cat unittest-files/python-return-code.py 
from sys import exit
exit(99)
Run Code Online (Sandbox Code Playgroud)

运行它:

$ ./call unittest-files/python-return-code.py 
$ echo $?
99
Run Code Online (Sandbox Code Playgroud)

必须执行一个文件,而不是一个命令.

Den*_*ach 6

PyRun_SimpleFileExFlags函数(以及使用它的所有函数,包括它PyRun_AnyFileEx)通过退出SystemExit或打印回溯来处理异常.使用PyRun_File*函数族来处理周围代码中的异常.

  • 不错的解决方案。现在使用PyRun_FileEx()并在PyErr_GivenExceptionMatches()之前检查PyErr_Occurred()。谢谢。 (2认同)