Catching SystemExit in C API code when embedding Python?

Farshid Lashkari no at spam.com
Thu Aug 2 15:11:20 EDT 2007


Stefan Bellon wrote:
> Hi all!
> 
> I am embedding Python into a GUI application in a way that the GUI is
> scriptable using Python.
> 
> Now I have come to a problem that when the user puts a "sys.exit(0)"
> into his script to end the script, not only the script is terminated,
> but also the GUI application itself. This is not the intended behaviour.
> 
> 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?
> 
> Thanks in advance for any hints.
> 

Have a look at the following doc page for handling exceptions with the C 
api:

http://docs.python.org/api/exceptionHandling.html

Also, here is some sample code that will catch system exit exceptions:

//Call python code
...
//Check for system exit exception
if(PyErr_Occurred()) {
     if(PyErr_ExceptionMatches(PyExc_SystemExit)) {
         //handle system exit
         PyErr_Clear();
     } else {
         PyErr_Print();
     }
}



More information about the Python-list mailing list