changing exceptions in C code

Rick L. Ratzel rick.ratzel at scd.magma-da.com
Thu May 6 16:58:27 EDT 2004


    If you're simply interested in adding info to the printed traceback, 
then this would be easier:

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

    PyErr_Print() is just printing to stderr...you should be able to do 
the same.  If you're really needing to prepend to the actual traceback 
object though, then your approach is probably the way to go.

-Rick Ratzel


Thomas Heller wrote:
> 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