changing exceptions in C code

Thomas Heller theller at python.net
Thu May 6 15:07:36 EDT 2004


I'm calling into Python code from C with PyObject_CallObject().  If the
python function raises an exception, the above code returns NULL, and I
want to print out the exception with PyErr_Print().

For whatever reasons, I want to prepend a short string "(in callback)"
to the error message itself:

    result = PyObject_CallObject(callable, arglist);
    if (!result) {
        Extend_Error_Info("(in callback)");
        PyErr_Print();
    }

I figured out this code for the Extend_Error_Info function:

void Extend_Error_Info(char *fmt, ...)
{
	va_list vargs;
	PyObject *tp, *v, *tb, *s;

	va_start(vargs, fmt);
	s = PyString_FromFormatV(fmt, vargs);
	va_end(vargs);
	if (!s)
		return;

	PyErr_Fetch(&tp, &v, &tb);
	PyErr_NormalizeException(&tp, &v, &tb);
	PyString_ConcatAndDel(&s, PyObject_Str(v));
	Py_DECREF(v);
	PyErr_Restore(tp, s, tb);
}

Does this look ok by the experts?

TIA,

Thomas





More information about the Python-list mailing list