Print a traceback from an extension?

Fredrik Lundh fredrik at pythonware.com
Sun Jul 14 07:26:41 EDT 2002


<gb at cs.unc.edu> wrote:

> Can I print a traceback from within a extension written in C?
>
> I know we're supposed to just keep returning NULL until we make it
> back to the main loop. That normally works fine.
>
> But I'm calling Python code from a callback that is called by C
> code. The Python code fails so PyEval_CallObject returns NULL. I want
> to provide a helpful message at that point.
>
> Can this be done? If so, can someone suggest where to look for an
> example?

I usually use a small helper like this one:

static void
report_error(const char* message)
{
    PyObject* sys_stderr;

    sys_stderr = PySys_GetObject("stderr");

    if (sys_stderr) {
        PyFile_WriteString("*** error in my library: ", sys_stderr);
        PyFile_WriteString((char*) message, sys_stderr);
        PyFile_WriteString(" (see traceback for details):\n", sys_stderr);
    }

    PyErr_Print();
    PyErr_Clear();
}

...

function = PyEval_CallObject(...)
if (!function)
    report_error("sorry, cannot call your object")

</F>

<!-- (the eff-bot guide to) the python standard library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list