Python C API:如何获取异常的字符串表示形式?

发布于 2024-07-24 21:51:10 字数 511 浏览 3 评论 0原文

如果我(例如)

 open("/snafu/fnord")

在Python中执行此操作(并且该文件不存在),我会收到回溯和消息

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

“我想使用Python的C API(即嵌入C程序中的Python解释器)获取上述字符串”。 我需要它作为字符串,而不是输出到控制台。

使用 PyErr_Fetch() 我可以获取异常的类型对象和值。 对于上面的示例,该值是一个元组:

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

是否有一种简单的方法可以将我从 PyErr_Fetch() 获取的信息转换为 Python 解释器显示的字符串? (不涉及您自己为每种异常类型构造此类字符串。)

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.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

随心而道 2024-07-31 21:51:10

我认为 Python 异常是通过在异常实例上运行“str()”来打印的,这将返回您感兴趣的格式化字符串。您可以通过调用 PyObject_Str() 此处描述的方法:

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

祝你好运!

更新:我有点困惑为什么PyErr_Fetch()返回给您的第二个元素是一个字符串。 我的猜测是,您收到“非标准化异常”,需要调用 PyErr_NormalizeException() 将该元组转换为“真正的”异常,该异常可以将自身格式化为您想要的字符串。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文