[capi-sig] Getting full traceback text

Campbell Barton ideasman42 at gmail.com
Thu Jan 15 05:57:49 CET 2009


recently I have been experimenting with a new api for blender3d, one
of the things it needs to be able to do is give python errors
(tracebacks) to our own error reporting api.

The problem is that Python/C api has no way to get the text that
PyErr_Print() prints, as a string.

This seems not such an unusual thing for an api to require, after all,
many applications dont run with a console to display text.

So far I think there are 3 ways to do this.
* Create a pipe, open it with fdopen(), then temporarily replace
stderr and stdout and call PyErr_Print().... then get the text from
that pipe. I havnt tried this yet and I'm not sure if its a good cross
platform solution.
* Copy and paste Pythons C traceback function into my own function
that builds a string rather then printing it. This really isnt an
attractive option.
* Use pythons traceback module from C (this isnt so bad, but Id prefer
not to have core parts of our api relying on *.py modules)

Is there some other way to do this? or is anyone currently doing this
in their application?

Here is the Python 3.x C api code for getting the traceback.
-------------------- snip

static void pyop_error_report(ReportList *reports)
{
	/*
	# in python this would be...
	import traceback
	string = ' '.join(traceback.format_exc())
	*/
	PyObject *type, *value, *traceback;

	PyObject *mod;
	PyObject *ret, *list, *string, *args;
	
	/* Save the current exception */
	PyErr_Fetch(&type, &value, &traceback);

	mod = PyImport_ImportModule("traceback");
	if (!mod) {
		/* print some error */
		return;
	}

	list= PyObject_CallMethod(mod, "format_exception", "OOO", type,
value, traceback);

	string= PyUnicode_FromString("\n");
	ret= PyUnicode_Join(string, list);
	Py_DECREF(list);
	Py_DECREF(string);

	BKE_report(reports, RPT_ERROR, _PyUnicode_AsString(ret));
	Py_DECREF(ret);
	PyErr_Clear();
}
--------------------

-- 
- Campbell


More information about the capi-sig mailing list