如何通过boost::python捕获python站点的自定义异常
How to catch custom exception of python site by boost::python
使用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/
相关文章:
- C++ 中的自定义异常:在哪里定义它们?
- 我应该C++自定义异常代码放在哪里?
- 自定义异常中的用户定义的空构造函数,具有多个继承和抽象基类
- 处理许多自定义异常的最佳方法是什么
- C++未显示自定义异常消息
- 自定义异常中的消息已损坏
- 为什么要创建自己的自定义异常类
- C++ 构造函数中的自定义异常抛出 ()
- JNI自定义异常具有多个参数
- 如何在抛出未处理的自定义异常后调用 what()?
- 无法创建两个从 std::logic_error 继承的自定义异常类
- 引发异常并直接结束程序的自定义异常处理
- 在C++中创建自定义异常
- G++ 自定义异常处理程序
- 自定义异常并不总是执行 what()
- 从boost::exception和std::runtime_error继承自定义异常类
- 添加到方法的 C++ 自定义异常会出错
- Boost.Python自定义异常类
- 如何通过boost::python捕获python站点的自定义异常
- 使用SWIG动态地将自定义C++异常重新考虑为Python异常