【问题标题】:How to prevent embedded python to exit() my process如何防止嵌入式python退出()我的进程
【发布时间】:2013-08-30 15:39:13
【问题描述】:

我在运行嵌入式 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;
}

另外,我的脚本是:

$ cat unittest-files/python-return-code.py 
from sys import exit
exit(99)

运行它:

$ ./call unittest-files/python-return-code.py 
$ echo $?
99

必须执行文件,而不是命令。

【问题讨论】:

    标签: python exception embedded exit


    【解决方案1】:

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

    【讨论】:

    • 不错的解决方案。现在使用 PyRun_FileEx() 并在 PyErr_GivenExceptionMatches() 之前检查 PyE​​rr_Occurred()。谢谢。
    猜你喜欢
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 2017-10-23
    • 2010-11-01
    • 1970-01-01
    • 2013-10-26
    • 2020-04-04
    相关资源
    最近更新 更多