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