blob: 0533beaf8c324103bfeb665836d377fb98a37b51 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001: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
R. David Murraye02a3012009-04-27 18:38:19 +000017the :data:`sys.last_traceback` variable and returned as the third item from
Georg Brandl116aa622007-08-15 14:28:22 +000018:func:`sys.exc_info`.
19
20The module defines the following functions:
21
22
Georg Brandl7f01a132009-09-16 15:58:14 +000023.. function:: print_tb(traceback, limit=None, file=None)
Georg Brandl116aa622007-08-15 14:28:22 +000024
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
Georg Brandl7f01a132009-09-16 15:58:14 +000031.. function:: print_exception(type, value, traceback, limit=None, file=None, chain=True)
Georg Brandl116aa622007-08-15 14:28:22 +000032
33 Print exception information and up to *limit* stack trace entries from
Georg Brandl1aea30a2008-07-19 15:51:07 +000034 *traceback* to *file*. This differs from :func:`print_tb` in the following
35 ways:
36
37 * if *traceback* is not ``None``, it prints a header ``Traceback (most recent
38 call last):``
39 * it prints the exception *type* and *value* after the stack trace
40 * if *type* is :exc:`SyntaxError` and *value* has the appropriate format, it
41 prints the line where the syntax error occurred with a caret indicating the
42 approximate position of the error.
43
44 If *chain* is true (the default), then chained exceptions (the
45 :attr:`__cause__` or :attr:`__context__` attributes of the exception) will be
46 printed as well, like the interpreter itself does when printing an unhandled
47 exception.
Georg Brandl116aa622007-08-15 14:28:22 +000048
49
Georg Brandl7f01a132009-09-16 15:58:14 +000050.. function:: print_exc(limit=None, file=None, chain=True)
Georg Brandl116aa622007-08-15 14:28:22 +000051
Georg Brandlf6945182008-02-01 11:56:49 +000052 This is a shorthand for ``print_exception(*sys.exc_info())``.
Georg Brandl116aa622007-08-15 14:28:22 +000053
54
Georg Brandl7f01a132009-09-16 15:58:14 +000055.. function:: print_last(limit=None, file=None, chain=True)
Georg Brandl116aa622007-08-15 14:28:22 +000056
57 This is a shorthand for ``print_exception(sys.last_type, sys.last_value,
R. David Murraye02a3012009-04-27 18:38:19 +000058 sys.last_traceback, limit, file)``. In general it will work only after
59 an exception has reached an interactive prompt (see :data:`sys.last_type`).
Georg Brandl116aa622007-08-15 14:28:22 +000060
61
Georg Brandl7f01a132009-09-16 15:58:14 +000062.. function:: print_stack(f=None, limit=None, file=None)
Georg Brandl116aa622007-08-15 14:28:22 +000063
64 This function prints a stack trace from its invocation point. The optional *f*
65 argument can be used to specify an alternate stack frame to start. The optional
66 *limit* and *file* arguments have the same meaning as for
67 :func:`print_exception`.
68
69
Georg Brandl7f01a132009-09-16 15:58:14 +000070.. function:: extract_tb(traceback, limit=None)
Georg Brandl116aa622007-08-15 14:28:22 +000071
72 Return a list of up to *limit* "pre-processed" stack trace entries extracted
73 from the traceback object *traceback*. It is useful for alternate formatting of
74 stack traces. If *limit* is omitted or ``None``, all entries are extracted. A
75 "pre-processed" stack trace entry is a quadruple (*filename*, *line number*,
76 *function name*, *text*) representing the information that is usually printed
77 for a stack trace. The *text* is a string with leading and trailing whitespace
78 stripped; if the source is not available it is ``None``.
79
80
Georg Brandl7f01a132009-09-16 15:58:14 +000081.. function:: extract_stack(f=None, limit=None)
Georg Brandl116aa622007-08-15 14:28:22 +000082
83 Extract the raw traceback from the current stack frame. The return value has
84 the same format as for :func:`extract_tb`. The optional *f* and *limit*
85 arguments have the same meaning as for :func:`print_stack`.
86
87
88.. function:: format_list(list)
89
90 Given a list of tuples as returned by :func:`extract_tb` or
91 :func:`extract_stack`, return a list of strings ready for printing. Each string
92 in the resulting list corresponds to the item with the same index in the
93 argument list. Each string ends in a newline; the strings may contain internal
94 newlines as well, for those items whose source text line is not ``None``.
95
96
97.. function:: format_exception_only(type, value)
98
99 Format the exception part of a traceback. The arguments are the exception type
100 and value such as given by ``sys.last_type`` and ``sys.last_value``. The return
101 value is a list of strings, each ending in a newline. Normally, the list
102 contains a single string; however, for :exc:`SyntaxError` exceptions, it
103 contains several lines that (when printed) display detailed information about
104 where the syntax error occurred. The message indicating which exception
105 occurred is the always last string in the list.
106
107
Georg Brandl7f01a132009-09-16 15:58:14 +0000108.. function:: format_exception(type, value, tb, limit=None, chain=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000109
110 Format a stack trace and the exception information. The arguments have the
111 same meaning as the corresponding arguments to :func:`print_exception`. The
112 return value is a list of strings, each ending in a newline and some containing
113 internal newlines. When these lines are concatenated and printed, exactly the
114 same text is printed as does :func:`print_exception`.
115
116
Georg Brandl7f01a132009-09-16 15:58:14 +0000117.. function:: format_exc(limit=None, chain=True)
Georg Brandl1aea30a2008-07-19 15:51:07 +0000118
119 This is like ``print_exc(limit)`` but returns a string instead of printing to a
120 file.
121
122
Georg Brandl7f01a132009-09-16 15:58:14 +0000123.. function:: format_tb(tb, limit=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000124
125 A shorthand for ``format_list(extract_tb(tb, limit))``.
126
127
Georg Brandl7f01a132009-09-16 15:58:14 +0000128.. function:: format_stack(f=None, limit=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000129
130 A shorthand for ``format_list(extract_stack(f, limit))``.
131
132
Georg Brandl116aa622007-08-15 14:28:22 +0000133.. _traceback-example:
134
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000135Traceback Examples
136------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138This simple example implements a basic read-eval-print loop, similar to (but
139less useful than) the standard Python interactive interpreter loop. For a more
140complete implementation of the interpreter loop, refer to the :mod:`code`
141module. ::
142
143 import sys, traceback
144
145 def run_user_code(envdir):
Georg Brandl8d5c3922007-12-02 22:48:17 +0000146 source = input(">>> ")
Georg Brandl116aa622007-08-15 14:28:22 +0000147 try:
148 exec(source, envdir)
Andrew Svetlov47395612012-11-02 22:07:26 +0200149 except Exception:
Collin Winterc79461b2007-09-01 23:34:30 +0000150 print("Exception in user code:")
151 print("-"*60)
Georg Brandl116aa622007-08-15 14:28:22 +0000152 traceback.print_exc(file=sys.stdout)
Collin Winterc79461b2007-09-01 23:34:30 +0000153 print("-"*60)
Georg Brandl116aa622007-08-15 14:28:22 +0000154
155 envdir = {}
Collin Winterc79461b2007-09-01 23:34:30 +0000156 while True:
Georg Brandl116aa622007-08-15 14:28:22 +0000157 run_user_code(envdir)
158
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000159
160The following example demonstrates the different ways to print and format the
R. David Murraye02a3012009-04-27 18:38:19 +0000161exception and traceback:
162
163.. testcode::
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000164
165 import sys, traceback
166
167 def lumberjack():
168 bright_side_of_death()
Georg Brandl48310cd2009-01-03 21:18:54 +0000169
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000170 def bright_side_of_death():
171 return tuple()[0]
Georg Brandl48310cd2009-01-03 21:18:54 +0000172
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000173 try:
174 lumberjack()
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000175 except IndexError:
176 exc_type, exc_value, exc_traceback = sys.exc_info()
Georg Brandlf6945182008-02-01 11:56:49 +0000177 print("*** print_tb:")
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000178 traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
Georg Brandlf6945182008-02-01 11:56:49 +0000179 print("*** print_exception:")
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000180 traceback.print_exception(exc_type, exc_value, exc_traceback,
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000181 limit=2, file=sys.stdout)
Georg Brandlf6945182008-02-01 11:56:49 +0000182 print("*** print_exc:")
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000183 traceback.print_exc()
Georg Brandlf6945182008-02-01 11:56:49 +0000184 print("*** format_exc, first and last line:")
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000185 formatted_lines = traceback.format_exc().splitlines()
Georg Brandlf6945182008-02-01 11:56:49 +0000186 print(formatted_lines[0])
187 print(formatted_lines[-1])
188 print("*** format_exception:")
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000189 print(repr(traceback.format_exception(exc_type, exc_value,
190 exc_traceback)))
Georg Brandlf6945182008-02-01 11:56:49 +0000191 print("*** extract_tb:")
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000192 print(repr(traceback.extract_tb(exc_traceback)))
Georg Brandlf6945182008-02-01 11:56:49 +0000193 print("*** format_tb:")
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000194 print(repr(traceback.format_tb(exc_traceback)))
195 print("*** tb_lineno:", exc_traceback.tb_lineno)
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000196
R. David Murraye02a3012009-04-27 18:38:19 +0000197The output for the example would look similar to this:
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000198
R. David Murraye02a3012009-04-27 18:38:19 +0000199.. testoutput::
200 :options: +NORMALIZE_WHITESPACE
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000201
202 *** print_tb:
R. David Murraye02a3012009-04-27 18:38:19 +0000203 File "<doctest...>", line 10, in <module>
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000204 lumberjack()
205 *** print_exception:
206 Traceback (most recent call last):
R. David Murraye02a3012009-04-27 18:38:19 +0000207 File "<doctest...>", line 10, in <module>
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000208 lumberjack()
R. David Murraye02a3012009-04-27 18:38:19 +0000209 File "<doctest...>", line 4, in lumberjack
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000210 bright_side_of_death()
211 IndexError: tuple index out of range
212 *** print_exc:
213 Traceback (most recent call last):
R. David Murraye02a3012009-04-27 18:38:19 +0000214 File "<doctest...>", line 10, in <module>
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000215 lumberjack()
R. David Murraye02a3012009-04-27 18:38:19 +0000216 File "<doctest...>", line 4, in lumberjack
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000217 bright_side_of_death()
218 IndexError: tuple index out of range
219 *** format_exc, first and last line:
220 Traceback (most recent call last):
221 IndexError: tuple index out of range
222 *** format_exception:
223 ['Traceback (most recent call last):\n',
R. David Murraye02a3012009-04-27 18:38:19 +0000224 ' File "<doctest...>", line 10, in <module>\n lumberjack()\n',
225 ' File "<doctest...>", line 4, in lumberjack\n bright_side_of_death()\n',
226 ' File "<doctest...>", line 7, in bright_side_of_death\n return tuple()[0]\n',
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000227 'IndexError: tuple index out of range\n']
228 *** extract_tb:
R. David Murraye02a3012009-04-27 18:38:19 +0000229 [('<doctest...>', 10, '<module>', 'lumberjack()'),
230 ('<doctest...>', 4, 'lumberjack', 'bright_side_of_death()'),
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000231 ('<doctest...>', 7, 'bright_side_of_death', 'return tuple()[0]')]
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000232 *** format_tb:
R. David Murraye02a3012009-04-27 18:38:19 +0000233 [' File "<doctest...>", line 10, in <module>\n lumberjack()\n',
234 ' File "<doctest...>", line 4, in lumberjack\n bright_side_of_death()\n',
235 ' File "<doctest...>", line 7, in bright_side_of_death\n return tuple()[0]\n']
236 *** tb_lineno: 10
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000237
238
239The following example shows the different ways to print and format the stack::
240
241 >>> import traceback
242 >>> def another_function():
243 ... lumberstack()
Georg Brandl48310cd2009-01-03 21:18:54 +0000244 ...
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000245 >>> def lumberstack():
246 ... traceback.print_stack()
Georg Brandlf6945182008-02-01 11:56:49 +0000247 ... print(repr(traceback.extract_stack()))
248 ... print(repr(traceback.format_stack()))
Georg Brandl48310cd2009-01-03 21:18:54 +0000249 ...
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000250 >>> another_function()
251 File "<doctest>", line 10, in <module>
252 another_function()
253 File "<doctest>", line 3, in another_function
254 lumberstack()
255 File "<doctest>", line 6, in lumberstack
256 traceback.print_stack()
257 [('<doctest>', 10, '<module>', 'another_function()'),
258 ('<doctest>', 3, 'another_function', 'lumberstack()'),
Georg Brandlf6945182008-02-01 11:56:49 +0000259 ('<doctest>', 7, 'lumberstack', 'print(repr(traceback.extract_stack()))')]
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000260 [' File "<doctest>", line 10, in <module>\n another_function()\n',
261 ' File "<doctest>", line 3, in another_function\n lumberstack()\n',
Georg Brandlf6945182008-02-01 11:56:49 +0000262 ' File "<doctest>", line 8, in lumberstack\n print(repr(traceback.format_stack()))\n']
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000263
264
R. David Murraye02a3012009-04-27 18:38:19 +0000265This last example demonstrates the final few formatting functions:
266
267.. doctest::
268 :options: +NORMALIZE_WHITESPACE
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000269
270 >>> import traceback
Georg Brandl0142d4a2009-04-27 16:22:44 +0000271 >>> traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'),
272 ... ('eggs.py', 42, 'eggs', 'return "bacon"')])
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000273 [' File "spam.py", line 3, in <module>\n spam.eggs()\n',
274 ' File "eggs.py", line 42, in eggs\n return "bacon"\n']
Georg Brandl0142d4a2009-04-27 16:22:44 +0000275 >>> an_error = IndexError('tuple index out of range')
276 >>> traceback.format_exception_only(type(an_error), an_error)
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000277 ['IndexError: tuple index out of range\n']