How to format traceback objects in Python

olamundo picture olamundo · Sep 4, 2009 · Viewed 22.7k times · Source

I have a traceback object that I want to show in the nice format I get when calling traceback.format_exc().

Is there a builtin function for this? Or a few lines of code?

Answer

Martin v. Löwis picture Martin v. Löwis · Sep 4, 2009

format_exc is really just

    etype, value, tb = sys.exc_info()
    return ''.join(format_exception(etype, value, tb, limit))

So if you have the exception type, value, and traceback ready, it should be easy. If you have just the exception, notice that format_exception is essentially.

    list = ['Traceback (most recent call last):\n']
    list = list + format_tb(tb, limit)

where limit defaults to None.