traceback over C API and PyObject_CallObject

Sami Vaisanen ensiferum_ at hotmail.com
Fri Oct 19 12:53:03 EDT 2007


Hello group,

I'm trying to get the Python exception information (message and traceback)
stored into a string in my C++ code. However all i get back is the string
"None". All the checks pass and all pointers get a value from the python
API calls. I've also tried with a different function such as
PyObject_CallFunctionObjArgs but the result is the same.

Thanks

void get_python_exception(string& message, string& traceback)
{
    GIL g;
 
    PyObject* type  = NULL;
    PyObject* value = NULL;
    PyObject* trace = NULL;
 
    PyErr_Fetch(&type, &value, &trace);
 
    py_ref ref_type(type);
    py_ref ref_value(value);
    py_ref ref_trace(trace);
 
    py_ref name(PyString_FromString("traceback"));
    py_ref module(PyImport_Import(name.get()));
    if (module)
    {
        py_ref fun(PyObject_GetAttrString(module.get(), "format_exc"));
        if (fun)
        {
            PyErr_Restore(type, value, trace);
            ref_type.release();
            ref_value.release();
            ref_trace.release();
 
            py_ref ret(PyObject_CallObject(fun.get(), NULL));
            if (ret && PyString_Check(ret.get()))
            {
                char* str = PyString_AsString(ret.get());
                message = str;
                traceback = "traceback not available";
                return;
            }
        }
    }
    message   = "message not available";
    traceback = "traceback not available";
}





More information about the Python-list mailing list