Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python C API: how to get string representation of exception?

If I do (e.g.)

 open("/snafu/fnord")

in Python (and the file does not exist), I get a traceback and the message

 IOError: [Errno 2] No such file or directory: '/snafu/fnord'

I would like to get the above string with Python's C API (i.e., a Python interpreter embedded in a C program). I need it as a string, not output to the console.

With PyErr_Fetch() I can get the type object of the exception and the value. For the above example, the value is a tuple:

 (2, 'No such file or directory', '/snafu/fnord')

Is there an easy way from the information I get from PyErr_Fetch() to the string the Python interpreter shows? (One that does not involve to construct such strings for each exception type yourself.)

like image 567
ashcatch Avatar asked Jun 16 '09 12:06

ashcatch


People also ask

How do you show exception messages in Python?

To catch and print an exception that occurred in a code snippet, wrap it in an indented try block, followed by the command "except Exception as e" that catches the exception and saves its error message in string variable e . You can now print the error message with "print(e)" or use it for further processing.

What is BaseException in Python?

The BaseException is the base class of all other exceptions. User defined classes cannot be directly derived from this class, to derive user defied class, we need to use Exception class. The Python Exception Hierarchy is like below.

How do you chain exceptions in Python?

To chain exceptions, use the raise from statement instead of a simple raise statement. This will give you information about both errors. except ValueError as e: raise RuntimeError( 'A parsing error occurred' ) from e...

What is except exception as e?

In contrast, the except Exception as e statement is a statement that defines an argument to the except statement. e in the latter statement is utilized to create an instance of the given Exception in the code and makes all of the attributes of the given Exception object accessible to the user.31-Dec-2021.


1 Answers

I think that Python exceptions are printed by running "str()" on the exception instance, which will return the formatted string you're interested in. You can get this from C by calling the PyObject_Str() method described here:

https://docs.python.org/c-api/object.html

Good luck!

Update: I'm a bit confused why the second element being returned to you by PyErr_Fetch() is a string. My guess is that you are receiving an "unnormalized exception" and need to call PyErr_NormalizeException() to turn that tuple into a "real" Exception that can format itself as a string like you want it to.

like image 183
Brandon Rhodes Avatar answered Oct 17 '22 22:10

Brandon Rhodes