我想在我的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;
}

PyErr_Print()只是将错误文本打印到stderr并清除错误,因此无法解决问题

有帮助吗?

解决方案

好吧,我发现了怎么做。

没有提升(只有错误信息,因为从回溯中提取信息的代码太重而无法在此处发布):

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);

和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

其他提示

这是迄今为止我能够提出的最强大的方法:

    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);
}

在Python C API中, PyObject_Str 返回对Python字符串对象的新引用,其中包含您作为参数传递的Python对象的字符串形式 - 就像Python代码中的 str(o)一样。请注意,异常对象没有“行号”之类的信息。 - 那是在追溯对象中(您可以使用 < code> PyErr_Fetch 获取异常对象和traceback对象)。不知道Boost提供了什么(如果有的话)使这些特定的C API函数更容易使用,但是,最坏的情况是,你总是可以使用这些函数,因为它们是在C API本身提供的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top