Getting error message/trace over the C API

Thomas Heller theller at ctypes.org
Tue Oct 16 14:05:10 EDT 2007


Sami Vaisanen schrieb:
> Hello group,
>  
> I'm writing a C++ based application that embeds the python engine. Now I
> have a problem regarding exception/error information. Is there a way to
> get the exception message and possibly the traceback into a string for
> example? I've been eyeballing the PyErr_ module and it seems fairly
> limited. In other words PyErr_Print() calls the right functions for
> getting the exception information but unfortunately it is hardwired to
> print this data directly into sys.stderr, and for an embedded application
> this is completely inappropriate. 
>  
> I have seen solutions that propose writing a custom Python class with
> write method and using that to grab the output from sys.stderr and then
> saving the data for example into a variable for later access, but unless
> Im mistaken this solution (not only that it is extremely ugly) is not
> thread safe. Even if a thread in my application is holding GIL, the lock
> can be released by extensions/the interpreter and thus opens up a race
> condition regarding that grabber object. 

You should call 'import traceback; traceback.format_exc()' from your C code;
it returns a string (a 'PyObject *' that contains a string).

Thomas




More information about the Python-list mailing list