blob: b68a8f1e1971df69c7bd00a412edc24434c6783a [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
Andrew Kuchling173a1572013-09-15 18:15:56 -0400132.. function:: clear_frames(tb)
133
134 Clears the local variables of all the stack frames in a traceback *tb*
135 by calling the :meth:`clear` method of each frame object.
136
137 .. versionadded:: 3.4
138
Georg Brandl116aa622007-08-15 14:28:22 +0000139
Georg Brandl116aa622007-08-15 14:28:22 +0000140.. _traceback-example:
141
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000142Traceback Examples
143------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000144
145This simple example implements a basic read-eval-print loop, similar to (but
146less useful than) the standard Python interactive interpreter loop. For a more
147complete implementation of the interpreter loop, refer to the :mod:`code`
148module. ::
149
150 import sys, traceback
151
152 def run_user_code(envdir):
Georg Brandl8d5c3922007-12-02 22:48:17 +0000153 source = input(">>> ")
Georg Brandl116aa622007-08-15 14:28:22 +0000154 try:
155 exec(source, envdir)
Andrew Svetlov47395612012-11-02 22:07:26 +0200156 except Exception:
Collin Winterc79461b2007-09-01 23:34:30 +0000157 print("Exception in user code:")
158 print("-"*60)
Georg Brandl116aa622007-08-15 14:28:22 +0000159 traceback.print_exc(file=sys.stdout)
Collin Winterc79461b2007-09-01 23:34:30 +0000160 print("-"*60)
Georg Brandl116aa622007-08-15 14:28:22 +0000161
162 envdir = {}
Collin Winterc79461b2007-09-01 23:34:30 +0000163 while True:
Georg Brandl116aa622007-08-15 14:28:22 +0000164 run_user_code(envdir)
165
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000166
167The following example demonstrates the different ways to print and format the
R. David Murraye02a3012009-04-27 18:38:19 +0000168exception and traceback:
169
170.. testcode::
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000171
172 import sys, traceback
173
174 def lumberjack():
175 bright_side_of_death()
Georg Brandl48310cd2009-01-03 21:18:54 +0000176
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000177 def bright_side_of_death():
178 return tuple()[0]
Georg Brandl48310cd2009-01-03 21:18:54 +0000179
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000180 try:
181 lumberjack()
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000182 except IndexError:
183 exc_type, exc_value, exc_traceback = sys.exc_info()
Georg Brandlf6945182008-02-01 11:56:49 +0000184 print("*** print_tb:")
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000185 traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
Georg Brandlf6945182008-02-01 11:56:49 +0000186 print("*** print_exception:")
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000187 traceback.print_exception(exc_type, exc_value, exc_traceback,
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000188 limit=2, file=sys.stdout)
Georg Brandlf6945182008-02-01 11:56:49 +0000189 print("*** print_exc:")
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000190 traceback.print_exc()
Georg Brandlf6945182008-02-01 11:56:49 +0000191 print("*** format_exc, first and last line:")
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000192 formatted_lines = traceback.format_exc().splitlines()
Georg Brandlf6945182008-02-01 11:56:49 +0000193 print(formatted_lines[0])
194 print(formatted_lines[-1])
195 print("*** format_exception:")
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000196 print(repr(traceback.format_exception(exc_type, exc_value,
197 exc_traceback)))
Georg Brandlf6945182008-02-01 11:56:49 +0000198 print("*** extract_tb:")
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000199 print(repr(traceback.extract_tb(exc_traceback)))
Georg Brandlf6945182008-02-01 11:56:49 +0000200 print("*** format_tb:")
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000201 print(repr(traceback.format_tb(exc_traceback)))
202 print("*** tb_lineno:", exc_traceback.tb_lineno)
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000203
R. David Murraye02a3012009-04-27 18:38:19 +0000204The output for the example would look similar to this:
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000205
R. David Murraye02a3012009-04-27 18:38:19 +0000206.. testoutput::
207 :options: +NORMALIZE_WHITESPACE
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000208
209 *** print_tb:
R. David Murraye02a3012009-04-27 18:38:19 +0000210 File "<doctest...>", line 10, in <module>
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000211 lumberjack()
212 *** print_exception:
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 *** print_exc:
220 Traceback (most recent call last):
R. David Murraye02a3012009-04-27 18:38:19 +0000221 File "<doctest...>", line 10, in <module>
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000222 lumberjack()
R. David Murraye02a3012009-04-27 18:38:19 +0000223 File "<doctest...>", line 4, in lumberjack
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000224 bright_side_of_death()
225 IndexError: tuple index out of range
226 *** format_exc, first and last line:
227 Traceback (most recent call last):
228 IndexError: tuple index out of range
229 *** format_exception:
230 ['Traceback (most recent call last):\n',
R. David Murraye02a3012009-04-27 18:38:19 +0000231 ' File "<doctest...>", line 10, in <module>\n lumberjack()\n',
232 ' File "<doctest...>", line 4, in lumberjack\n bright_side_of_death()\n',
233 ' File "<doctest...>", line 7, in bright_side_of_death\n return tuple()[0]\n',
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000234 'IndexError: tuple index out of range\n']
235 *** extract_tb:
R. David Murraye02a3012009-04-27 18:38:19 +0000236 [('<doctest...>', 10, '<module>', 'lumberjack()'),
237 ('<doctest...>', 4, 'lumberjack', 'bright_side_of_death()'),
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000238 ('<doctest...>', 7, 'bright_side_of_death', 'return tuple()[0]')]
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000239 *** format_tb:
R. David Murraye02a3012009-04-27 18:38:19 +0000240 [' File "<doctest...>", line 10, in <module>\n lumberjack()\n',
241 ' File "<doctest...>", line 4, in lumberjack\n bright_side_of_death()\n',
242 ' File "<doctest...>", line 7, in bright_side_of_death\n return tuple()[0]\n']
243 *** tb_lineno: 10
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000244
245
246The following example shows the different ways to print and format the stack::
247
248 >>> import traceback
249 >>> def another_function():
250 ... lumberstack()
Georg Brandl48310cd2009-01-03 21:18:54 +0000251 ...
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000252 >>> def lumberstack():
253 ... traceback.print_stack()
Georg Brandlf6945182008-02-01 11:56:49 +0000254 ... print(repr(traceback.extract_stack()))
255 ... print(repr(traceback.format_stack()))
Georg Brandl48310cd2009-01-03 21:18:54 +0000256 ...
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000257 >>> another_function()
258 File "<doctest>", line 10, in <module>
259 another_function()
260 File "<doctest>", line 3, in another_function
261 lumberstack()
262 File "<doctest>", line 6, in lumberstack
263 traceback.print_stack()
264 [('<doctest>', 10, '<module>', 'another_function()'),
265 ('<doctest>', 3, 'another_function', 'lumberstack()'),
Georg Brandlf6945182008-02-01 11:56:49 +0000266 ('<doctest>', 7, 'lumberstack', 'print(repr(traceback.extract_stack()))')]
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000267 [' File "<doctest>", line 10, in <module>\n another_function()\n',
268 ' File "<doctest>", line 3, in another_function\n lumberstack()\n',
Georg Brandlf6945182008-02-01 11:56:49 +0000269 ' File "<doctest>", line 8, in lumberstack\n print(repr(traceback.format_stack()))\n']
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000270
271
R. David Murraye02a3012009-04-27 18:38:19 +0000272This last example demonstrates the final few formatting functions:
273
274.. doctest::
275 :options: +NORMALIZE_WHITESPACE
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000276
277 >>> import traceback
Georg Brandl0142d4a2009-04-27 16:22:44 +0000278 >>> traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'),
279 ... ('eggs.py', 42, 'eggs', 'return "bacon"')])
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000280 [' File "spam.py", line 3, in <module>\n spam.eggs()\n',
281 ' File "eggs.py", line 42, in eggs\n return "bacon"\n']
Georg Brandl0142d4a2009-04-27 16:22:44 +0000282 >>> an_error = IndexError('tuple index out of range')
283 >>> traceback.format_exception_only(type(an_error), an_error)
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000284 ['IndexError: tuple index out of range\n']