Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get exception information after a call to PyRun_String(...) returns NULL?

I am trying to run the following code:

Py_Initialize();
PyObject *py_main = PyImport_AddModule("__main__");
PyObject *py_dict = PyModule_GetDict(py_main);
PyObject *ret = PyRun_String(SOME_PYTHON_CODE, Py_file_input, py_dict, py_dict);

But it seems there is an error somewhere in my generated python code (SOME_PYTHON_CODE) and so ret comes out as NULL indicating an exception was raised. How can I get access to this exception?

like image 554
Matt Avatar asked Oct 15 '25 16:10

Matt


1 Answers

You can do:

PyErr_Print();

To get a standard stack trace printed out on standard error. There are other more fine tuned function calls to handle errors, but I believe this is the simplest, bare bones approach.

And here is a question/answer about accessing the traceback objects. One of the answers shows how to get the backtrace copied into a C string, which you could then write to file (or GUI in your case).

like image 132
mshildt Avatar answered Oct 17 '25 06:10

mshildt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!