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

本文关键字:API Python 处理 already error 中的 python set Boost 什么      更新时间:2023-10-16

我一直在做一个项目,我想删除提升依赖项并将其替换为Python C API。

我花了一些时间了解Python C API,我看到了这个 catch (error_already_set const &)

我阅读了提升文档,但它解释了它的使用位置。但是我想知道为什么需要它,以及如何使用本机Python C api实现相同的功能。

Boost 在发生 Python 错误时抛出error_already_set。 因此,如果您看到这样的代码:

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++异常(。