2011-04-04 56 views
8

我在运行嵌入式python时遇到了麻烦。事实证明,我无法捕获由sys.exit()引发的SystemExit异常;如何防止嵌入式python退出()我的过程

这是我到目前为止有:

$ 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 

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

回答

5

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

+1

不错的解决方案。现在使用PyRun_FileEx()并在PyErr_GivenExceptionMatches()之前检查PyErr_Occurred()。谢谢。 – Caruccio 2011-04-04 17:47:29