Python C API:如何获取异常的字符串表示形式? [英] Python C API: how to get string representation of exception?
问题描述
如果我愿意(例如)
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'
我想使用Python的C API(即,嵌入在C程序中的Python解释器)获得上述字符串。我需要它作为字符串,而不是输出到控制台。
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.
使用 PyErr_Fetch()
可以得到类型异常的对象和值。对于上面的示例,该值是一个元组:
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')
从我从 PyErr_Fetch获得的信息中是否有简便的方法()
到Python解释器显示的字符串? (一个不涉及自己为每种异常类型构造此类字符串的字符串。)
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.)
推荐答案
我认为Python异常是通过以下方式打印的:在异常实例上运行 str(),它将返回您感兴趣的格式化字符串。您可以通过调用 PyObject_Str()
方法,如下所述:
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
祝你好运!
更新:我有些困惑,为什么 PyErr_Fetch()
返回给您的第二个元素是字符串。我的猜测是,您收到一个未规范化的异常,需要调用 PyErr_NormalizeException()
将该元组变成真实的异常,该异常可以将自身格式化为类似于您想要它。
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.
这篇关于Python C API:如何获取异常的字符串表示形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!