如何用boost::python捕捉python站点的自定义异常

2024-05-16 17:58:51 发布

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

使用pythonldap连接ldap服务器,一切正常,但是我不知道如何识别python抛出的特定异常ldap。那里有许多来自python ldap的自定义异常,如“ldap.SERVER_关闭", "超过ldap.SIZELIMIT_", "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,ldif\n"
           "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;
  }
}

我怎么知道pythonldap抛出了哪个异常?我可以通过“格式异常”打印出消息,但这个解决方案远不理想。在


Tags: importobjectserverincludemainldapnamespacepythonldap
1条回答
网友
1楼 · 发布于 2024-05-16 17:58:51

使用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/

相关问题 更多 >