Example #1
0
/**
 * Extract the exception error string from the python interpreter.
 *
 * This function assumes the gil is acquired. See \ref python_thread_guard.
 *
 * Code adapted from http://stackoverflow.com/questions/1418015/how-to-get-python-exception-text
 */
std::string parse_python_error() {
  PyObject *exc,*val,*tb;
  PyErr_Fetch(&exc,&val,&tb);
  PyErr_NormalizeException(&exc,&val,&tb);
  python::handle<> hexc(exc),hval(python::allow_null(val)),htb(python::allow_null(tb));
  if(!hval) {
    return python::extract<std::string>(python::str(hexc));
  }
  else {
    python::object traceback(python::import("traceback"));
    python::object format_exception(traceback.attr("format_exception"));
    python::object formatted_list(format_exception(hexc,hval,htb));
    python::object formatted(python::str("").join(formatted_list));
    return python::extract<std::string>(formatted);
  }
}
Example #2
0
/// Adapted from http://stackoverflow.com/a/6576177/1689220
std::string pyerr_to_string(void)
{
    PyObject *exc, *val, *tb;
    bp::object formatted_list, formatted;
    PyErr_Fetch(&exc, &val, &tb);
    // wrap exception, value, traceback with bp::handle for auto memory management
    bp::handle<> hexc(exc), hval(bp::allow_null(val)), htb(bp::allow_null(tb));
    // import "traceback" module
    bp::object traceback(bp::import("traceback"));
    if (!tb) {
        bp::object format_exception_only(traceback.attr("format_exception_only"));
        formatted_list = format_exception_only(hexc, hval);
    } else {
        bp::object format_exception(traceback.attr("format_exception"));
        formatted_list = format_exception(hexc, hval, htb);
    }
    formatted = bp::str("\n").join(formatted_list);
    return bp::extract<std::string>(formatted);
}