如何通过pybDN11在Python中从C++中捕获异常?

2024-09-30 14:25:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pybind11用python编写代码

例如,我有test1.cpp、test_pybind.cpp和example.py

heaan_pybind.cpp

namespace py=pybind11;
PYBIND11_MODULE(test, m)
{
  py::class_<test1>(m, "test1")
  .def("fn", ...)
}

在example.py中,我想控制异常,如下所示

import test
while True:
  try:
    test.test1.fn(...)
  except ???:
    print("exception error.")

如何从example.py中的test.cpp捕获错误或异常


Tags: 代码pytestexampledefnamespacecppclass
2条回答

如果您不知道异常的类型,只需捕获最一般的类型,如Exception。见下文

import test
while True:
  try:
    test.test1.fn(...)
  except Exception:
    print("exception error.")

微不足道的方法是确保所有要在Python中捕获的C++异常也是绑定的一部分。

因此,在您的模块中,假设您有一个名为CppExp的cpp异常类型,您可以执行以下操作

namespace py=pybind11;
PYBIND11_MODULE(test, m)
{
  py::register_exception<CppExp>(module, "PyExp");
}

这将创建一个名为PyExp的新python异常,并将导致抛出CppExp的任何代码将其重新映射到python异常中

然后在python代码中可以执行以下操作

import test
while True:
  try:
    test.test1.fn(...)
  except test.PyExp as ex:
    print("exception error.", ex)

关于异常处理的其他pybind11文档如下: https://pybind11.readthedocs.io/en/master/advanced/exceptions.html

<如果你的C++异常有你想翻译成Python的自定义字段或方法,你必须根据我的答案实际修改pybDun11代码: How can you bind exceptions with custom fields and constructors in pybind11 and still have them function as python exception?

相关问题 更多 >