1:mod:`traceback` --- Print or retrieve a stack traceback 2======================================================== 3 4.. module:: traceback 5 :synopsis: Print or retrieve a stack traceback. 6 7 8This module provides a standard interface to extract, format and print stack 9traces of Python programs. It exactly mimics the behavior of the Python 10interpreter when it prints a stack trace. This is useful when you want to print 11stack traces under program control, such as in a "wrapper" around the 12interpreter. 13 14.. index:: object: traceback 15 16The module uses traceback objects --- this is the object type that is stored in 17the variables :data:`sys.exc_traceback` (deprecated) and 18:data:`sys.last_traceback` and returned as the third item from 19:func:`sys.exc_info`. 20 21The module defines the following functions: 22 23 24.. function:: print_tb(tb[, limit[, file]]) 25 26 Print up to *limit* stack trace entries from the traceback object *tb*. If 27 *limit* is omitted or ``None``, all entries are printed. If *file* is omitted 28 or ``None``, the output goes to ``sys.stderr``; otherwise it should be an 29 open file or file-like object to receive the output. 30 31 32.. function:: print_exception(etype, value, tb[, limit[, file]]) 33 34 Print exception information and up to *limit* stack trace entries from the 35 traceback *tb* to *file*. This differs from :func:`print_tb` in the following 36 ways: (1) if *tb* is not ``None``, it prints a header ``Traceback (most 37 recent call last):``; (2) it prints the exception *etype* and *value* after 38 the stack trace; (3) if *etype* is :exc:`SyntaxError` and *value* has the 39 appropriate format, it prints the line where the syntax error occurred with a 40 caret indicating the approximate position of the error. 41 42 43.. function:: print_exc([limit[, file]]) 44 45 This is a shorthand for ``print_exception(sys.exc_type, sys.exc_value, 46 sys.exc_traceback, limit, file)``. (In fact, it uses :func:`sys.exc_info` to 47 retrieve the same information in a thread-safe way instead of using the 48 deprecated variables.) 49 50 51.. function:: format_exc([limit]) 52 53 This is like ``print_exc(limit)`` but returns a string instead of printing to 54 a file. 55 56 .. versionadded:: 2.4 57 58 59.. function:: print_last([limit[, file]]) 60 61 This is a shorthand for ``print_exception(sys.last_type, sys.last_value, 62 sys.last_traceback, limit, file)``. In general it will work only after 63 an exception has reached an interactive prompt (see :data:`sys.last_type`). 64 65 66.. function:: print_stack([f[, limit[, file]]]) 67 68 This function prints a stack trace from its invocation point. The optional 69 *f* argument can be used to specify an alternate stack frame to start. The 70 optional *limit* and *file* arguments have the same meaning as for 71 :func:`print_exception`. 72 73 74.. function:: extract_tb(tb[, limit]) 75 76 Return a list of up to *limit* "pre-processed" stack trace entries extracted 77 from the traceback object *tb*. It is useful for alternate formatting of 78 stack traces. If *limit* is omitted or ``None``, all entries are extracted. 79 A "pre-processed" stack trace entry is a 4-tuple (*filename*, *line number*, 80 function name*, *text*) representing the information that is usually printed 81 for a stack trace. The *text* is a string with leading and trailing 82 whitespace stripped; if the source is not available it is ``None``. 83 84 85.. function:: extract_stack([f[, limit]]) 86 87 Extract the raw traceback from the current stack frame. The return value has 88 the same format as for :func:`extract_tb`. The optional *f* and *limit* 89 arguments have the same meaning as for :func:`print_stack`. 90 91 92.. function:: format_list(extracted_list) 93 94 Given a list of tuples as returned by :func:`extract_tb` or 95 :func:`extract_stack`, return a list of strings ready for printing. Each 96 string in the resulting list corresponds to the item with the same index in 97 the argument list. Each string ends in a newline; the strings may contain 98 internal newlines as well, for those items whose source text line is not 99 ``None``. 100 101 102.. function:: format_exception_only(etype, value) 103 104 Format the exception part of a traceback. The arguments are the exception 105 type, *etype* and *value* such as given by ``sys.last_type`` and 106 ``sys.last_value``. The return value is a list of strings, each ending in a 107 newline. Normally, the list contains a single string; however, for 108 :exc:`SyntaxError` exceptions, it contains several lines that (when printed) 109 display detailed information about where the syntax error occurred. The 110 message indicating which exception occurred is the always last string in the 111 list. 112 113 114.. function:: format_exception(etype, value, tb[, limit]) 115 116 Format a stack trace and the exception information. The arguments have the 117 same meaning as the corresponding arguments to :func:`print_exception`. The 118 return value is a list of strings, each ending in a newline and some 119 containing internal newlines. When these lines are concatenated and printed, 120 exactly the same text is printed as does :func:`print_exception`. 121 122 123.. function:: format_tb(tb[, limit]) 124 125 A shorthand for ``format_list(extract_tb(tb, limit))``. 126 127 128.. function:: format_stack([f[, limit]]) 129 130 A shorthand for ``format_list(extract_stack(f, limit))``. 131 132 133.. function:: tb_lineno(tb) 134 135 This function returns the current line number set in the traceback object. 136 This function was necessary because in versions of Python prior to 2.3 when 137 the :option:`-O` flag was passed to Python the ``tb.tb_lineno`` was not 138 updated correctly. This function has no use in versions past 2.3. 139 140 141.. _traceback-example: 142 143Traceback Examples 144------------------ 145 146This simple example implements a basic read-eval-print loop, similar to (but 147less useful than) the standard Python interactive interpreter loop. For a more 148complete implementation of the interpreter loop, refer to the :mod:`code` 149module. :: 150 151 import sys, traceback 152 153 def run_user_code(envdir): 154 source = raw_input(">>> ") 155 try: 156 exec source in envdir 157 except: 158 print "Exception in user code:" 159 print '-'*60 160 traceback.print_exc(file=sys.stdout) 161 print '-'*60 162 163 envdir = {} 164 while 1: 165 run_user_code(envdir) 166 167 168The following example demonstrates the different ways to print and format the 169exception and traceback:: 170 171 import sys, traceback 172 173 def lumberjack(): 174 bright_side_of_death() 175 176 def bright_side_of_death(): 177 return tuple()[0] 178 179 try: 180 lumberjack() 181 except IndexError: 182 exc_type, exc_value, exc_traceback = sys.exc_info() 183 print "*** print_tb:" 184 traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) 185 print "*** print_exception:" 186 traceback.print_exception(exc_type, exc_value, exc_traceback, 187 limit=2, file=sys.stdout) 188 print "*** print_exc:" 189 traceback.print_exc() 190 print "*** format_exc, first and last line:" 191 formatted_lines = traceback.format_exc().splitlines() 192 print formatted_lines[0] 193 print formatted_lines[-1] 194 print "*** format_exception:" 195 print repr(traceback.format_exception(exc_type, exc_value, 196 exc_traceback)) 197 print "*** extract_tb:" 198 print repr(traceback.extract_tb(exc_traceback)) 199 print "*** format_tb:" 200 print repr(traceback.format_tb(exc_traceback)) 201 print "*** tb_lineno:", exc_traceback.tb_lineno 202 203 204The output for the example would look similar to this:: 205 206 *** print_tb: 207 File "<doctest...>", line 10, in <module> 208 lumberjack() 209 *** print_exception: 210 Traceback (most recent call last): 211 File "<doctest...>", line 10, in <module> 212 lumberjack() 213 File "<doctest...>", line 4, in lumberjack 214 bright_side_of_death() 215 IndexError: tuple index out of range 216 *** print_exc: 217 Traceback (most recent call last): 218 File "<doctest...>", line 10, in <module> 219 lumberjack() 220 File "<doctest...>", line 4, in lumberjack 221 bright_side_of_death() 222 IndexError: tuple index out of range 223 *** format_exc, first and last line: 224 Traceback (most recent call last): 225 IndexError: tuple index out of range 226 *** format_exception: 227 ['Traceback (most recent call last):\n', 228 ' File "<doctest...>", line 10, in <module>\n lumberjack()\n', 229 ' File "<doctest...>", line 4, in lumberjack\n bright_side_of_death()\n', 230 ' File "<doctest...>", line 7, in bright_side_of_death\n return tuple()[0]\n', 231 'IndexError: tuple index out of range\n'] 232 *** extract_tb: 233 [('<doctest...>', 10, '<module>', 'lumberjack()'), 234 ('<doctest...>', 4, 'lumberjack', 'bright_side_of_death()'), 235 ('<doctest...>', 7, 'bright_side_of_death', 'return tuple()[0]')] 236 *** format_tb: 237 [' File "<doctest...>", line 10, in <module>\n lumberjack()\n', 238 ' File "<doctest...>", line 4, in lumberjack\n bright_side_of_death()\n', 239 ' File "<doctest...>", line 7, in bright_side_of_death\n return tuple()[0]\n'] 240 *** tb_lineno: 10 241 242 243The following example shows the different ways to print and format the stack:: 244 245 >>> import traceback 246 >>> def another_function(): 247 ... lumberstack() 248 ... 249 >>> def lumberstack(): 250 ... traceback.print_stack() 251 ... print repr(traceback.extract_stack()) 252 ... print repr(traceback.format_stack()) 253 ... 254 >>> another_function() 255 File "<doctest>", line 10, in <module> 256 another_function() 257 File "<doctest>", line 3, in another_function 258 lumberstack() 259 File "<doctest>", line 6, in lumberstack 260 traceback.print_stack() 261 [('<doctest>', 10, '<module>', 'another_function()'), 262 ('<doctest>', 3, 'another_function', 'lumberstack()'), 263 ('<doctest>', 7, 'lumberstack', 'print repr(traceback.extract_stack())')] 264 [' File "<doctest>", line 10, in <module>\n another_function()\n', 265 ' File "<doctest>", line 3, in another_function\n lumberstack()\n', 266 ' File "<doctest>", line 8, in lumberstack\n print repr(traceback.format_stack())\n'] 267 268 269This last example demonstrates the final few formatting functions: 270 271.. doctest:: 272 :options: +NORMALIZE_WHITESPACE 273 274 >>> import traceback 275 >>> traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'), 276 ... ('eggs.py', 42, 'eggs', 'return "bacon"')]) 277 [' File "spam.py", line 3, in <module>\n spam.eggs()\n', 278 ' File "eggs.py", line 42, in eggs\n return "bacon"\n'] 279 >>> an_error = IndexError('tuple index out of range') 280 >>> traceback.format_exception_only(type(an_error), an_error) 281 ['IndexError: tuple index out of range\n'] 282