如何通过boost::python捕获python站点的自定义异常

How to catch custom exception of python site by boost::python

本文关键字:python 自定义异常 站点 捕获 何通过 boost      更新时间:2023-10-16

使用python ldap与ldap服务器连接,一切都很好,但我不知道如何识别由python ldap抛出的特定异常。有许多来自python ldap的自定义异常,如"ldap。SERVER_DOWN"、"ldap。SIZELIMIT_EXCEEDED"、"ldap。

示例代码:

#include <iostream>
#define BOOST_PYTHON_STATIC_LIB
#include <boost/python.hpp>
int main()
{
  namespace bp = boost::python;
  try{
      Py_Initialize();
      bp::object main_module = bp::import("__main__");
      bp::import("ldap");
      bp::import("ldif");
      bp::object main_namespace = main_module.attr("__dict__");
      bp::exec("import ldap,ldifn"
           "l = ldap.initialize('ldaps://RIO-PC')n"
           "l.whoami_s()n",
           main_namespace);
      //do something
  }catch (boost::python::error_already_set const &) {
  if (PyErr_Occurred()) {
      //find out it is exception "ldap.SERVER_DOWN"?
  }
      PyErr_Clear();
  }catch (std::exception const &ex) {
      std::cout<<ex.what()<<std::endl;
  }
}

我怎么知道python ldap抛出了哪个异常?我可以通过"format_exception"打印出消息,但这种解决方案远非理想。

使用PyErr_GivenExceptionMatches:

object LdapServerDownException = bp::import("ldap").attr("SERVER_DOWN") ;
# ...
PyObject *e;
if ((e = PyErr_Occured())) {
    if (PyErr_GivenExceptionMatches(e, LdapServerDownException.ptr())) {
    }
}

见http://misspent.wordpress.com/2009/10/11/boost-python-and-handling-python-exceptions/