Embedding -- getting error/traceback information not to stderr?

Jon K Hellan hellan at acm.org
Tue Jan 25 09:53:02 EST 2000


erw at dde.dk (Erwin S. Andreasen) writes:

> In my application using embedded Python, I'd like to print out the error
> information as it occurrs (traceback, etc.). This is what PyErr_PrintEx()
> (called from PyErr_Print()) does -- unfortunately, it does it to sys.stderr.

I don't know if you want a solution in Python or C. Python solutions have
been given. Here's an example in C:
 
static char *
convert_py_exception_to_string ()
{
	char *header = _("Python exception");
	char *retval = header;
	char buf [256];
	int pos;
	
	PyObject *ptype = NULL, *pvalue = NULL, *ptraceback = NULL;
	PyObject *stype = NULL, *svalue = NULL;
	
	PyErr_Fetch (&ptype, &pvalue, &ptraceback);
	if (!ptype)
		goto cleanup;
	stype = PyObject_Str (ptype);
	if (!stype)
		goto cleanup;
	pos = snprintf (buf, sizeof buf, "%s: %s",
			header, PyString_AsString (stype));
	retval = buf;
	
	if (pvalue && (pos + 3 < sizeof buf))
		svalue = PyObject_Str (pvalue);
	if (!svalue)
		goto cleanup;
	snprintf (buf + pos , sizeof buf - pos , ": %s",
			PyString_AsString (svalue));
cleanup:
	Py_XDECREF (stype);
	Py_XDECREF (svalue);
	PyErr_Restore (ptype, pvalue, ptraceback);

	return strdup (retval);
}

The function returns a string without the traceback info. You'll
probably want to include the traceback. I call PyErr_Restore in case I
also want traceback to the console.

HTH

Jon



More information about the Python-list mailing list