Example 2-18 demonstrates that the traceback module allows you Program Print abnormal trace return
(Traceback) information, similar to what the interpreter did when no exception was captured. As shown in example 2-18. 2.11.0.1. Example
2-18. Use the traceback module to print trace return information file: traceback-example-1.py # note!
Import
Example 2-18 shows the traceback module that allows you to print the trace return (traceback) Information of exceptions in the program, similar to what the interpreter did when exceptions were not captured, as shown in example 2-18.
2.11.0.1. Example 2-18. Use the traceback module to print the trace return information.
File: traceback-example-1.py
# Note! Importing the traceback module messes up
# Exception state, so you better do that here and not
# In the exception handler
# Note! Importing traceback will clear the exception status, so
# Do not handle exceptionsCodeImport this module
Import traceback
Try:
Raise syntaxerror, "example"
Except t:
Traceback. print_exc ()
Traceback (innermost last ):
File "traceback-example-1.py", line 7, in?
Syntaxerror: Example
Example 2-19 use the stringio module to put the tracing return information in the string.
2.11.0.2. Example 2-19. Use the traceback module to copy the trace return information to the string.
File: traceback-example-2.py
Import traceback
Import stringio
Try:
Raise ioerror, "an I/O error occurred"
Except t:
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):/012 File
Traceback-example-2.py, line 5, in? /012 ioerror: an I/O Error
Occurred/012'
You can use the extract_tb function to format the trace return information and obtain a list containing error information, as shown in example 2-20.
2.11.0.3. Example 2-20. Use the traceback module to encode the traceback object.
file: traceback-example-3.py
Import traceback
Import sys
def function ():
raise ioerror, "an I/O error occurred"
try:
function ()
failed T:
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]
traceb Ack-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