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


# note! importing the traceback module messes up the
# exception state, so you better do that here and not
# in the exception handler
import traceback

 raise SyntaxError, "example"

Traceback (innermost last):
 File "", 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


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):12 File
"", line 5, in ?12IOError: an i/o error

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


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

Core Modules

More Standard Modules

Threads and Processes

Data Representation

File Formats

Mail and News Message Processing

Network Protocols


Multimedia Modules

Data Storage

Tools and Utilities

Platform-Specific Modules

Implementation Support Modules

Other Modules

Python Standard Library
Python Standard Library (Nutshell Handbooks) with
ISBN: 0596000960
EAN: 2147483647
Year: 2000
Pages: 252
Authors: Fredrik Lundh © 2008-2020.
If you may any questions please contact us: