The traceback module

This module allows you to print exception tracebacks inside your programs, just like the interpreter does when you don’t catch an exception yourself.

Example: Using the traceback module to print a traceback
# File:

# note! in old Python versions, importing the traceback
# messes up the exception state.  to be on the safe side,
# let's import it here.
import traceback

    raise SyntaxError, "example"

Traceback (innermost last):
  File "", line 9, in ?
SyntaxError: example

To put the traceback in a string, use the StringIO module:

Example: Using the traceback module to copy a traceback to a string
# File:

import traceback
import StringIO

    raise IOError, "an i/o error occurred"
    fp = StringIO.StringIO()
    message = fp.getvalue()

    print "failure! the error was:", repr(message)

failure! the error was: 'Traceback (innermost last):\012  File
"", line 5, in ?\012IOError: an i/o error

If you wish to format the traceback in a non-standard way, you can use the extract_tb function to convert a traceback object to a list of stack entries:

Example: Using the traceback module to decode a traceback object
# File:

import traceback
import sys

def function():
    raise IOError, "an i/o error occurred"

    info = sys.exc_info()
    for file, lineno, function, text in traceback.extract_tb(info[2]):
        print file, "line", lineno, "in", function
        print "=>", repr(text)
    print "** %s: %s" % info[:2] line 8 in ?
=> 'function()' line 5 in function
=> 'raise IOError, "an i/o error occurred"'
** exceptions.IOError: an i/o error occurred

A Django site. rendered by a django application. hosted by webfaction.