traceback over C API and PyObject_CallObject

Discussion in 'Python' started by Sami Vaisanen, Oct 19, 2007.

  1. 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.


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

    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";
    message = "message not available";
    traceback = "traceback not available";
    Sami Vaisanen, Oct 19, 2007
    1. Advertisements

  2. This is what you get (actually "None\n") when there is no error set.
    Since you already know the three components (type, value, trace), I'd use
    traceback.format_exception instead (and remove the PyErr_Restore call -
    I'm unsure if it works the way you expect it).
    In this case you have to pass three arguments, so yes, use
    PyObject_CallFunctionObjArgs (remember the final NULL). Beware:
    format_exception returns a formatted list, not a string. You have to
    concatenate all the elements (either using ''.join or repeteadly calling
    Gabriel Genellina, Oct 20, 2007
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.