Ant*_*lev 46 c++ python exception boost-python
我想在我的C++应用程序中嵌入python.我正在使用Boost库 - 很棒的工具.但我有一个问题.
如果python函数抛出异常,我想抓住它并在我的应用程序中打印错误或获取一些详细信息,如python脚本中的行号导致错误.
我该怎么做?我找不到任何函数来获取Python API或Boost中的详细异常信息.
try {
module=import("MyModule"); //this line will throw excetion if MyModule contains an error
} catch ( error_already_set const & ) {
//Here i can said that i have error, but i cant determine what caused an error
std::cout << "error!" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
PyErr_Print()只是将错误文本输出到stderr并清除错误,因此无法解决问题
Ant*_*lev 55
好吧,我发现了怎么做.
没有boost(只有错误消息,因为从traceback中提取信息的代码太重而无法在此处发布):
PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
//pvalue contains error message
//ptraceback contains stack snapshot and many other information
//(see python traceback structure)
//Get error message
char *pStrErrorMessage = PyString_AsString(pvalue);
Run Code Online (Sandbox Code Playgroud)
和BOOST版本
try{
//some code that throws an error
}catch(error_already_set &){
PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
handle<> hType(ptype);
object extype(hType);
handle<> hTraceback(ptraceback);
object traceback(hTraceback);
//Extract error message
string strErrorMessage = extract<string>(pvalue);
//Extract line number (top entry of call stack)
// if you want to extract another levels of call stack
// also process traceback.attr("tb_next") recurently
long lineno = extract<long> (traceback.attr("tb_lineno"));
string filename = extract<string>(traceback.attr("tb_frame").attr("f_code").attr("co_filename"));
string funcname = extract<string>(traceback.attr("tb_frame").attr("f_code").attr("co_name"));
... //cleanup here
Run Code Online (Sandbox Code Playgroud)
mah*_*mah 20
这是迄今为止我能够提出的最强大的方法:
try {
...
}
catch (bp::error_already_set) {
if (PyErr_Occurred()) {
msg = handle_pyerror();
}
py_exception = true;
bp::handle_exception();
PyErr_Clear();
}
if (py_exception)
....
// decode a Python exception into a string
std::string handle_pyerror()
{
using namespace boost::python;
using namespace boost;
PyObject *exc,*val,*tb;
object formatted_list, formatted;
PyErr_Fetch(&exc,&val,&tb);
handle<> hexc(exc),hval(allow_null(val)),htb(allow_null(tb));
object traceback(import("traceback"));
if (!tb) {
object format_exception_only(traceback.attr("format_exception_only"));
formatted_list = format_exception_only(hexc,hval);
} else {
object format_exception(traceback.attr("format_exception"));
formatted_list = format_exception(hexc,hval,htb);
}
formatted = str("\n").join(formatted_list);
return extract<std::string>(formatted);
}
Run Code Online (Sandbox Code Playgroud)
在Python C API中,PyObject_Str返回对Python字符串对象的新引用,其中包含您作为参数传递的Python对象的字符串形式 - 就像str(o)在Python代码中一样.请注意,异常对象没有"行号"之类的信息 - 它位于traceback对象中(您可以使用它PyErr_Fetch来获取异常对象和traceback对象).不知道Boost提供了什么(如果有的话)使这些特定的C API函数更容易使用,但是,最坏的情况是,你总是可以使用C API本身提供的这些函数.