Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent embedded python to exit() my process

I'm having trouble while running embedded python. It turns out that I can't capture that SystemExit exception raised by sys.exit();

This is what I have so far:

$ 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;
}

Also, my script is:

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

Running it:

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

I must execute a file, not a command.

like image 271
Caruccio Avatar asked Apr 04 '11 14:04

Caruccio


1 Answers

PyRun_SimpleFileExFlags function (and all functions using it, including PyRun_AnyFileEx) handles exceptions itself by exiting for SystemExit or printing traceback. Use PyRun_File* family of functions to handle exceptions in surrounding code.

like image 91
Denis Otkidach Avatar answered Nov 03 '22 15:11

Denis Otkidach