returning traceback strings

Matthew Boedicker mboedick at
Thu Jun 13 18:11:09 EDT 2002


I am looking for something exactly like traceback.print_exc(), but instead
of writing the traceback text to a filehandle, I want it to return it to
me as a string.  I was unable to find any way to do this using the traceback
module, since everything there seems to be in terms of file handles being
passed around.

The problem is I need to pass the entire multi-line traceback string to a
file-like object's write() method in one call, not line by line.

This is the best workaround I was able to come up with:

import cStringIO
import traceback

def print_exc_str():
    buf = cStringIO.StringIO()
    return buf.getvalue()

Any suggestions for a better way?  What about the traceback module using
strings internally, and wrapping another layer around that to write to files
and file-like objects?

Matthew Boedicker

More information about the Python-list mailing list