gpt4 book ai didi

python - Boost.python 中的 error_already_set 做了什么以及如何在 Python C API 中类似地处理异常

转载 作者:太空狗 更新时间:2023-10-29 20:35:22 31 4
gpt4 key购买 nike

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

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

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

最佳答案

当发生 Python 错误时,Boost 抛出 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++ 异常)。

关于python - Boost.python 中的 error_already_set 做了什么以及如何在 Python C API 中类似地处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43094001/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com