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

前端 未结 1 1022
忘了有多久
忘了有多久 2021-02-20 06:35

If I do (e.g.)

 open(\"/snafu/fnord\")

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

 IOError: [Er         


        
1条回答
  •  余生分开走
    2021-02-20 07:27

    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.

    0 讨论(0)
提交回复
热议问题