Exception handling and traceback from Python/C API

Trasan Apansson martin.segersten at front.com
Wed Jan 30 12:12:36 EST 2002


Hi!

I'm trying to get a traceback with help of the function PyErr_Fetch.
It is, to be more specific, the third argument that I'm trying to get
hold of. I can't find any easy way to do that so could any one please
help me.

Please look at the code-example, at the end of this text, from
1997/08/15, in this group. It gives a good example on how to use
PyErr_Fetch despite of that it do not explain how get the traceback.

Regards

/Martin

include <Python.h>
#include <stdio.h>
char save_error_type[1024], save_error_info[1024];

PyerrorHandler(char *msgFromC)
{
    /* process Python-related errors */
    /* call after Python API raises an exception C detects */

    PyObject *errobj, *errdata, *errtraceback, *pystring;
    printf("%s\n", msgFromC); 

    /* get latest python exception info */ 
    PyErr_Fetch(&errobj, &errdata, &errtraceback);       /* increfs
all 3 */

    pystring = NULL;
    if (errobj != NULL &&
       (pystring = PyObject_Str(errobj)) != NULL &&      /*
str(errobj) */
       (PyString_Check(pystring))                        /* str():
increfs */
       )
        strcpy(save_error_type, PyString_AsString(pystring));   /*
Py->C */
    else 
        strcpy(save_error_type, "<unknown exception type>");
    Py_XDECREF(pystring);

    pystring = NULL;
    if (errdata != NULL &&
       (pystring = PyObject_Str(errdata)) != NULL &&     /* str():
increfs */
       (PyString_Check(pystring)) 
       )
        strcpy(save_error_info, PyString_AsString(pystring));   /*
Py->C */
    else 
        strcpy(save_error_info, "<unknown exception data>");
    Py_XDECREF(pystring);

    printf("%s\n%s\n", save_error_type, save_error_info);   
    Py_XDECREF(errobj);
    Py_XDECREF(errdata);         /* caller owns all 3 objects */
    Py_XDECREF(errtraceback);    /* already NULL'd out in Python */ 
}



More information about the Python-list mailing list