The traceback Module

The traceback module in Example 2-18 allows you to print exception tracebacks inside your programs, just like the interpreter does when you don't catch an exception yourself.

Example 2-18. Using the traceback Module to Print a Traceback

File: traceback-example-1.py # note! importing the traceback module messes up the # exception state, so you better do that here and not # in the exception handler import traceback try: raise SyntaxError, "example" except: traceback.print_exc() Traceback (innermost last): File "traceback-example-1.py", line 7, in ? SyntaxError: example

Example 2-19 uses the StringIO module to put the traceback in a string.

Example 2-19. Using the traceback Module to Copy a Traceback to a String

File: traceback-example-2.py import traceback import StringIO try: raise IOError, "an i/o error occurred" except: fp = StringIO.StringIO() traceback.print_exc(file=fp) message = fp.getvalue() print "failure! the error was:", repr(message) failure! the error was: 'Traceback (innermost last):12 File "traceback-example-2.py", line 5, in ?12IOError: an i/o error occurred12'

To format the traceback in a nonstandard way, use the extract_tb function to convert a traceback object to a list of stack entries, as Example 2-20 demonstrates.

Example 2-20. Using the traceback Module to Decode a Traceback Object

File: traceback-example-3.py import traceback import sys def function(): raise IOError, "an i/o error occurred" try: function() except: 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] traceback-example-3.py line 8 in ? => 'function()' traceback-example-3.py line 5 in function => 'raise IOError, "an i/o error occurred"' ** exceptions.IOError: an i/o error occurred

Категории