Boost.python中的error_already_set做什么,以及如何在Python C API中类似地处理异常 [英] What does error_already_set in Boost.python do and how to handle exceptions similarly in Python C API
问题描述
我一直在一个项目中,我想删除boost依赖项并用Python C API替换它。
I have been working on a project where I want to remove the boost dependencies and replace it with the Python C API.
我花了一些时间了解Python C API,我看到了这个
捕获(error_already_set const&)
I spent some time understanding the Python C API and I saw this
catch (error_already_set const &)
我阅读了boost文档它说明了它的使用位置。但是我想知道为什么需要它,以及如何使用本机Python C api实现相同的功能。
I read the boost docs but it explains where it is used. But I want to know why it is needed and how can I achieve the same functionality using the native Python C api.
推荐答案
Boost发生Python错误时,抛出 error_already_set
。因此,如果您看到这样的代码:
Boost throws error_already_set
when a Python error has occurred. So if you see code like this:
try {
bp::exec(bp::str("garbage code is garbage"));
} catch (const bp::error_already_set&) {
// your code here to examine Python traceback etc.
}
您将替换为:
your_ptr<PyObject> res = PyRun_String("garbage code is garbage");
if (!res) {
// your code here to examine Python traceback etc.
}
换句话说,无论什么地方看到 catch(error_already_set)
,您都可能想使用 PyObject *
或其他值可以识别何时发生错误(因此您可以检查回溯,或将其转换为C ++异常)。
In other words, wherever you see catch(error_already_set)
, there you will likely want to do some error handling using whatever PyObject*
or other value is involved to recognize when an error has occurred (and therefore you can examine the traceback, or convert it into a C++ exception).
这篇关于Boost.python中的error_already_set做什么,以及如何在Python C API中类似地处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!