Catching SystemExit in C API code when embedding Python?

Stefan Bellon sbellon at sbellon.de
Thu Aug 2 21:15:38 CEST 2007


First of all, I'm sorry to followup my own posting, but I can add a few
things ...

On Thu, 02 Aug, Stefan Bellon wrote:

> As in Python itself you can catch SystemExit, I think this should be
> the way to go. But how do I catch this exception from within the C
> API?

I now installed an exception hook in sys.excepthook on the C side. And
indeed, it gets called whenever an exception is raised ... but not when
SystemExit is raised. And indeed, in PyErr_PrintEx in pythonrun.c I
found the following:

        hook = PySys_GetObject("excepthook");
        if (hook) {
                PyObject *args = PyTuple_Pack(3,
                    exception, v ? v : Py_None, tb ? tb : Py_None);
                PyObject *result = PyEval_CallObject(hook, args);
                if (result == NULL) {
                        PyObject *exception2, *v2, *tb2;
                        if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
                                handle_system_exit();
                        }

But ... then my original question becomes even stronger: How do I
"catch" a SystemExit when embedding Python and not wanting that a
script with sys.exit just terminates the whole application?

-- 
Stefan Bellon



More information about the Python-list mailing list