blob: e938dd58b05312858253309146114efc8e51c56c [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
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04007**Source code:** :source:`Lib/traceback.py`
8
9--------------
Georg Brandl116aa622007-08-15 14:28:22 +000010
11This module provides a standard interface to extract, format and print stack
12traces of Python programs. It exactly mimics the behavior of the Python
13interpreter when it prints a stack trace. This is useful when you want to print
14stack traces under program control, such as in a "wrapper" around the
15interpreter.
16
17.. index:: object: traceback
18
19The module uses traceback objects --- this is the object type that is stored in
R. David Murraye02a3012009-04-27 18:38:19 +000020the :data:`sys.last_traceback` variable and returned as the third item from
Georg Brandl116aa622007-08-15 14:28:22 +000021:func:`sys.exc_info`.
22
23The module defines the following functions:
24
25
Senthil Kumarana82908f2016-01-15 21:45:17 -080026.. function:: print_tb(tb, limit=None, file=None)
Georg Brandl116aa622007-08-15 14:28:22 +000027
Senthil Kumarana82908f2016-01-15 21:45:17 -080028 Print up to *limit* stack trace entries from traceback object *tb* (starting
29 from the caller's frame) if *limit* is positive. Otherwise, print the last
30 ``abs(limit)`` entries. If *limit* is omitted or ``None``, all entries are
31 printed. If *file* is omitted or ``None``, the output goes to
32 ``sys.stderr``; otherwise it should be an open file or file-like object to
33 receive the output.
Serhiy Storchaka24559e42015-05-03 13:19:46 +030034
35 .. versionchanged:: 3.5
36 Added negative *limit* support.
Georg Brandl116aa622007-08-15 14:28:22 +000037
38
Zackery Spytz91e93792020-11-05 15:18:44 -070039.. function:: print_exception(exc, /[, value, tb], limit=None, \
40 file=None, chain=True)
Georg Brandl116aa622007-08-15 14:28:22 +000041
Senthil Kumarana82908f2016-01-15 21:45:17 -080042 Print exception information and stack trace entries from traceback object
43 *tb* to *file*. This differs from :func:`print_tb` in the following
Georg Brandl1aea30a2008-07-19 15:51:07 +000044 ways:
45
Senthil Kumarana82908f2016-01-15 21:45:17 -080046 * if *tb* is not ``None``, it prints a header ``Traceback (most recent
Georg Brandl1aea30a2008-07-19 15:51:07 +000047 call last):``
Serhiy Storchakaddb961d2018-10-26 09:00:49 +030048
Zackery Spytz91e93792020-11-05 15:18:44 -070049 * it prints the exception type and *value* after the stack trace
Serhiy Storchakaddb961d2018-10-26 09:00:49 +030050
Serhiy Storchaka913876d2018-10-28 13:41:26 +020051 .. index:: single: ^ (caret); marker
Serhiy Storchakaddb961d2018-10-26 09:00:49 +030052
Matthias Bussonniercdb89cd2017-06-01 14:54:01 -070053 * if *type(value)* is :exc:`SyntaxError` and *value* has the appropriate
54 format, it prints the line where the syntax error occurred with a caret
55 indicating the approximate position of the error.
Georg Brandl1aea30a2008-07-19 15:51:07 +000056
Zackery Spytz91e93792020-11-05 15:18:44 -070057 Since Python 3.10, instead of passing *value* and *tb*, an exception object
58 can be passed as the first argument. If *value* and *tb* are provided, the
59 first argument is ignored in order to provide backwards compatibility.
60
Serhiy Storchaka24559e42015-05-03 13:19:46 +030061 The optional *limit* argument has the same meaning as for :func:`print_tb`.
Georg Brandl1aea30a2008-07-19 15:51:07 +000062 If *chain* is true (the default), then chained exceptions (the
63 :attr:`__cause__` or :attr:`__context__` attributes of the exception) will be
64 printed as well, like the interpreter itself does when printing an unhandled
65 exception.
Georg Brandl116aa622007-08-15 14:28:22 +000066
Matthias Bussonniercdb89cd2017-06-01 14:54:01 -070067 .. versionchanged:: 3.5
68 The *etype* argument is ignored and inferred from the type of *value*.
69
Zackery Spytz91e93792020-11-05 15:18:44 -070070 .. versionchanged:: 3.10
71 The *etype* parameter has been renamed to *exc* and is now
72 positional-only.
73
Georg Brandl116aa622007-08-15 14:28:22 +000074
Georg Brandl7f01a132009-09-16 15:58:14 +000075.. function:: print_exc(limit=None, file=None, chain=True)
Georg Brandl116aa622007-08-15 14:28:22 +000076
Serhiy Storchaka24559e42015-05-03 13:19:46 +030077 This is a shorthand for ``print_exception(*sys.exc_info(), limit, file,
78 chain)``.
Georg Brandl116aa622007-08-15 14:28:22 +000079
80
Georg Brandl7f01a132009-09-16 15:58:14 +000081.. function:: print_last(limit=None, file=None, chain=True)
Georg Brandl116aa622007-08-15 14:28:22 +000082
83 This is a shorthand for ``print_exception(sys.last_type, sys.last_value,
Serhiy Storchaka24559e42015-05-03 13:19:46 +030084 sys.last_traceback, limit, file, chain)``. In general it will work only
85 after an exception has reached an interactive prompt (see
86 :data:`sys.last_type`).
Georg Brandl116aa622007-08-15 14:28:22 +000087
88
Georg Brandl7f01a132009-09-16 15:58:14 +000089.. function:: print_stack(f=None, limit=None, file=None)
Georg Brandl116aa622007-08-15 14:28:22 +000090
Serhiy Storchaka24559e42015-05-03 13:19:46 +030091 Print up to *limit* stack trace entries (starting from the invocation
92 point) if *limit* is positive. Otherwise, print the last ``abs(limit)``
93 entries. If *limit* is omitted or ``None``, all entries are printed.
94 The optional *f* argument can be used to specify an alternate stack frame
95 to start. The optional *file* argument has the same meaning as for
96 :func:`print_tb`.
97
98 .. versionchanged:: 3.5
99 Added negative *limit* support.
Georg Brandl116aa622007-08-15 14:28:22 +0000100
101
Senthil Kumarana82908f2016-01-15 21:45:17 -0800102.. function:: extract_tb(tb, limit=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000103
torsavaf394ee52018-08-02 17:08:59 +0100104 Return a :class:`StackSummary` object representing a list of "pre-processed"
105 stack trace entries extracted from the traceback object *tb*. It is useful
106 for alternate formatting of stack traces. The optional *limit* argument has
107 the same meaning as for :func:`print_tb`. A "pre-processed" stack trace
108 entry is a :class:`FrameSummary` object containing attributes
109 :attr:`~FrameSummary.filename`, :attr:`~FrameSummary.lineno`,
110 :attr:`~FrameSummary.name`, and :attr:`~FrameSummary.line` representing the
111 information that is usually printed for a stack trace. The
112 :attr:`~FrameSummary.line` is a string with leading and trailing
113 whitespace stripped; if the source is not available it is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000114
115
Georg Brandl7f01a132009-09-16 15:58:14 +0000116.. function:: extract_stack(f=None, limit=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000117
118 Extract the raw traceback from the current stack frame. The return value has
119 the same format as for :func:`extract_tb`. The optional *f* and *limit*
120 arguments have the same meaning as for :func:`print_stack`.
121
122
Senthil Kumarana82908f2016-01-15 21:45:17 -0800123.. function:: format_list(extracted_list)
Georg Brandl116aa622007-08-15 14:28:22 +0000124
torsavaf394ee52018-08-02 17:08:59 +0100125 Given a list of tuples or :class:`FrameSummary` objects as returned by
126 :func:`extract_tb` or :func:`extract_stack`, return a list of strings ready
127 for printing. Each string in the resulting list corresponds to the item with
128 the same index in the argument list. Each string ends in a newline; the
129 strings may contain internal newlines as well, for those items whose source
130 text line is not ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000131
132
Zackery Spytz91e93792020-11-05 15:18:44 -0700133.. function:: format_exception_only(exc, /[, value])
Georg Brandl116aa622007-08-15 14:28:22 +0000134
Zackery Spytz91e93792020-11-05 15:18:44 -0700135 Format the exception part of a traceback using an exception value such as
136 given by ``sys.last_value``. The return value is a list of strings, each
137 ending in a newline. Normally, the list contains a single string; however,
138 for :exc:`SyntaxError` exceptions, it contains several lines that (when
139 printed) display detailed information about where the syntax error occurred.
140 The message indicating which exception occurred is the always last string in
141 the list.
142
143 Since Python 3.10, instead of passing *value*, an exception object
144 can be passed as the first argument. If *value* is provided, the first
145 argument is ignored in order to provide backwards compatibility.
146
147 .. versionchanged:: 3.10
148 The *etype* parameter has been renamed to *exc* and is now
149 positional-only.
Georg Brandl116aa622007-08-15 14:28:22 +0000150
151
Zackery Spytz91e93792020-11-05 15:18:44 -0700152.. function:: format_exception(exc, /[, value, tb], limit=None, chain=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000153
154 Format a stack trace and the exception information. The arguments have the
155 same meaning as the corresponding arguments to :func:`print_exception`. The
Senthil Kumarana82908f2016-01-15 21:45:17 -0800156 return value is a list of strings, each ending in a newline and some
157 containing internal newlines. When these lines are concatenated and printed,
158 exactly the same text is printed as does :func:`print_exception`.
Georg Brandl116aa622007-08-15 14:28:22 +0000159
Matthias Bussonniercdb89cd2017-06-01 14:54:01 -0700160 .. versionchanged:: 3.5
161 The *etype* argument is ignored and inferred from the type of *value*.
162
Zackery Spytz91e93792020-11-05 15:18:44 -0700163 .. versionchanged:: 3.10
164 This function's behavior and signature were modified to match
165 :func:`print_exception`.
166
Georg Brandl116aa622007-08-15 14:28:22 +0000167
Georg Brandl7f01a132009-09-16 15:58:14 +0000168.. function:: format_exc(limit=None, chain=True)
Georg Brandl1aea30a2008-07-19 15:51:07 +0000169
Senthil Kumarana82908f2016-01-15 21:45:17 -0800170 This is like ``print_exc(limit)`` but returns a string instead of printing to
171 a file.
Georg Brandl1aea30a2008-07-19 15:51:07 +0000172
173
Georg Brandl7f01a132009-09-16 15:58:14 +0000174.. function:: format_tb(tb, limit=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000175
176 A shorthand for ``format_list(extract_tb(tb, limit))``.
177
178
Georg Brandl7f01a132009-09-16 15:58:14 +0000179.. function:: format_stack(f=None, limit=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000180
181 A shorthand for ``format_list(extract_stack(f, limit))``.
182
Andrew Kuchling173a1572013-09-15 18:15:56 -0400183.. function:: clear_frames(tb)
184
185 Clears the local variables of all the stack frames in a traceback *tb*
186 by calling the :meth:`clear` method of each frame object.
187
188 .. versionadded:: 3.4
189
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300190.. function:: walk_stack(f)
191
Berker Peksag49f373b2015-03-06 12:18:06 +0200192 Walk a stack following ``f.f_back`` from the given frame, yielding the frame
193 and line number for each frame. If *f* is ``None``, the current stack is
194 used. This helper is used with :meth:`StackSummary.extract`.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300195
196 .. versionadded:: 3.5
197
198.. function:: walk_tb(tb)
199
Berker Peksag49f373b2015-03-06 12:18:06 +0200200 Walk a traceback following ``tb_next`` yielding the frame and line number
201 for each frame. This helper is used with :meth:`StackSummary.extract`.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300202
203 .. versionadded:: 3.5
204
205The module also defines the following classes:
206
207:class:`TracebackException` Objects
208-----------------------------------
209
Berker Peksag49f373b2015-03-06 12:18:06 +0200210.. versionadded:: 3.5
211
212:class:`TracebackException` objects are created from actual exceptions to
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300213capture data for later printing in a lightweight fashion.
214
Irit Katriel4c94d742021-01-15 02:45:02 +0000215.. class:: TracebackException(exc_type, exc_value, exc_traceback, *, limit=None, lookup_lines=True, capture_locals=False, compact=False)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300216
Berker Peksag49f373b2015-03-06 12:18:06 +0200217 Capture an exception for later rendering. *limit*, *lookup_lines* and
218 *capture_locals* are as for the :class:`StackSummary` class.
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300219
Irit Katriel4c94d742021-01-15 02:45:02 +0000220 If *compact* is true, only data that is required by :class:`TracebackException`'s
221 ``format`` method is saved in the class attributes. In particular, the
222 ``__context__`` field is calculated only if ``__cause__`` is ``None`` and
223 ``__suppress_context__`` is false.
224
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300225 Note that when locals are captured, they are also shown in the traceback.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300226
Berker Peksag49f373b2015-03-06 12:18:06 +0200227 .. attribute:: __cause__
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300228
Berker Peksag49f373b2015-03-06 12:18:06 +0200229 A :class:`TracebackException` of the original ``__cause__``.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300230
Berker Peksag49f373b2015-03-06 12:18:06 +0200231 .. attribute:: __context__
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300232
Berker Peksag49f373b2015-03-06 12:18:06 +0200233 A :class:`TracebackException` of the original ``__context__``.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300234
Berker Peksag49f373b2015-03-06 12:18:06 +0200235 .. attribute:: __suppress_context__
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300236
Berker Peksag49f373b2015-03-06 12:18:06 +0200237 The ``__suppress_context__`` value from the original exception.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300238
Berker Peksag49f373b2015-03-06 12:18:06 +0200239 .. attribute:: stack
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300240
Berker Peksag49f373b2015-03-06 12:18:06 +0200241 A :class:`StackSummary` representing the traceback.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300242
Berker Peksag49f373b2015-03-06 12:18:06 +0200243 .. attribute:: exc_type
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300244
Berker Peksag49f373b2015-03-06 12:18:06 +0200245 The class of the original traceback.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300246
Berker Peksag49f373b2015-03-06 12:18:06 +0200247 .. attribute:: filename
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300248
Berker Peksag49f373b2015-03-06 12:18:06 +0200249 For syntax errors - the file name where the error occurred.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300250
Berker Peksag49f373b2015-03-06 12:18:06 +0200251 .. attribute:: lineno
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300252
Berker Peksag49f373b2015-03-06 12:18:06 +0200253 For syntax errors - the line number where the error occurred.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300254
Berker Peksag49f373b2015-03-06 12:18:06 +0200255 .. attribute:: text
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300256
Berker Peksag49f373b2015-03-06 12:18:06 +0200257 For syntax errors - the text where the error occurred.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300258
Berker Peksag49f373b2015-03-06 12:18:06 +0200259 .. attribute:: offset
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300260
Berker Peksag49f373b2015-03-06 12:18:06 +0200261 For syntax errors - the offset into the text where the error occurred.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300262
Berker Peksag49f373b2015-03-06 12:18:06 +0200263 .. attribute:: msg
264
265 For syntax errors - the compiler error message.
266
267 .. classmethod:: from_exception(exc, *, limit=None, lookup_lines=True, capture_locals=False)
268
269 Capture an exception for later rendering. *limit*, *lookup_lines* and
270 *capture_locals* are as for the :class:`StackSummary` class.
271
272 Note that when locals are captured, they are also shown in the traceback.
273
274 .. method:: format(*, chain=True)
275
276 Format the exception.
277
278 If *chain* is not ``True``, ``__cause__`` and ``__context__`` will not
279 be formatted.
280
281 The return value is a generator of strings, each ending in a newline and
282 some containing internal newlines. :func:`~traceback.print_exception`
283 is a wrapper around this method which just prints the lines to a file.
284
285 The message indicating which exception occurred is always the last
286 string in the output.
287
288 .. method:: format_exception_only()
289
290 Format the exception part of the traceback.
291
292 The return value is a generator of strings, each ending in a newline.
293
294 Normally, the generator emits a single string; however, for
295 :exc:`SyntaxError` exceptions, it emits several lines that (when
296 printed) display detailed information about where the syntax
297 error occurred.
298
299 The message indicating which exception occurred is always the last
300 string in the output.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300301
Irit Katriel4c94d742021-01-15 02:45:02 +0000302 .. versionchanged:: 3.10
303 Added the *compact* parameter.
304
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300305
306:class:`StackSummary` Objects
307-----------------------------
308
Berker Peksag49f373b2015-03-06 12:18:06 +0200309.. versionadded:: 3.5
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300310
Berker Peksag49f373b2015-03-06 12:18:06 +0200311:class:`StackSummary` objects represent a call stack ready for formatting.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300312
Berker Peksag49f373b2015-03-06 12:18:06 +0200313.. class:: StackSummary
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300314
Berker Peksag49f373b2015-03-06 12:18:06 +0200315 .. classmethod:: extract(frame_gen, *, limit=None, lookup_lines=True, capture_locals=False)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300316
Berker Peksag49f373b2015-03-06 12:18:06 +0200317 Construct a :class:`StackSummary` object from a frame generator (such as
318 is returned by :func:`~traceback.walk_stack` or
319 :func:`~traceback.walk_tb`).
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300320
Berker Peksag49f373b2015-03-06 12:18:06 +0200321 If *limit* is supplied, only this many frames are taken from *frame_gen*.
322 If *lookup_lines* is ``False``, the returned :class:`FrameSummary`
323 objects will not have read their lines in yet, making the cost of
324 creating the :class:`StackSummary` cheaper (which may be valuable if it
325 may not actually get formatted). If *capture_locals* is ``True`` the
326 local variables in each :class:`FrameSummary` are captured as object
327 representations.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300328
Berker Peksag49f373b2015-03-06 12:18:06 +0200329 .. classmethod:: from_list(a_list)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300330
torsavaf394ee52018-08-02 17:08:59 +0100331 Construct a :class:`StackSummary` object from a supplied list of
332 :class:`FrameSummary` objects or old-style list of tuples. Each tuple
333 should be a 4-tuple with filename, lineno, name, line as the elements.
Berker Peksag49f373b2015-03-06 12:18:06 +0200334
Nick Coghland0034232016-08-15 13:11:34 +1000335 .. method:: format()
336
337 Returns a list of strings ready for printing. Each string in the
338 resulting list corresponds to a single frame from the stack.
339 Each string ends in a newline; the strings may contain internal
340 newlines as well, for those items with source text lines.
341
342 For long sequences of the same frame and line, the first few
343 repetitions are shown, followed by a summary line stating the exact
344 number of further repetitions.
345
Nick Coghlan02d03df2016-08-16 10:58:14 +1000346 .. versionchanged:: 3.6
347 Long sequences of repeated frames are now abbreviated.
Nick Coghland0034232016-08-15 13:11:34 +1000348
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300349
350:class:`FrameSummary` Objects
351-----------------------------
352
Berker Peksag49f373b2015-03-06 12:18:06 +0200353.. versionadded:: 3.5
354
355:class:`FrameSummary` objects represent a single frame in a traceback.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300356
357.. class:: FrameSummary(filename, lineno, name, lookup_line=True, locals=None, line=None)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300358
359 Represent a single frame in the traceback or stack that is being formatted
360 or printed. It may optionally have a stringified version of the frames
Berker Peksag49f373b2015-03-06 12:18:06 +0200361 locals included in it. If *lookup_line* is ``False``, the source code is not
362 looked up until the :class:`FrameSummary` has the :attr:`~FrameSummary.line`
363 attribute accessed (which also happens when casting it to a tuple).
364 :attr:`~FrameSummary.line` may be directly provided, and will prevent line
365 lookups happening at all. *locals* is an optional local variable
366 dictionary, and if supplied the variable representations are stored in the
367 summary for later display.
Georg Brandl116aa622007-08-15 14:28:22 +0000368
Georg Brandl116aa622007-08-15 14:28:22 +0000369.. _traceback-example:
370
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000371Traceback Examples
372------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000373
374This simple example implements a basic read-eval-print loop, similar to (but
375less useful than) the standard Python interactive interpreter loop. For a more
376complete implementation of the interpreter loop, refer to the :mod:`code`
377module. ::
378
379 import sys, traceback
380
381 def run_user_code(envdir):
Georg Brandl8d5c3922007-12-02 22:48:17 +0000382 source = input(">>> ")
Georg Brandl116aa622007-08-15 14:28:22 +0000383 try:
384 exec(source, envdir)
Andrew Svetlov47395612012-11-02 22:07:26 +0200385 except Exception:
Collin Winterc79461b2007-09-01 23:34:30 +0000386 print("Exception in user code:")
387 print("-"*60)
Georg Brandl116aa622007-08-15 14:28:22 +0000388 traceback.print_exc(file=sys.stdout)
Collin Winterc79461b2007-09-01 23:34:30 +0000389 print("-"*60)
Georg Brandl116aa622007-08-15 14:28:22 +0000390
391 envdir = {}
Collin Winterc79461b2007-09-01 23:34:30 +0000392 while True:
Georg Brandl116aa622007-08-15 14:28:22 +0000393 run_user_code(envdir)
394
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000395
396The following example demonstrates the different ways to print and format the
R. David Murraye02a3012009-04-27 18:38:19 +0000397exception and traceback:
398
399.. testcode::
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000400
401 import sys, traceback
402
403 def lumberjack():
404 bright_side_of_death()
Georg Brandl48310cd2009-01-03 21:18:54 +0000405
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000406 def bright_side_of_death():
407 return tuple()[0]
Georg Brandl48310cd2009-01-03 21:18:54 +0000408
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000409 try:
410 lumberjack()
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000411 except IndexError:
412 exc_type, exc_value, exc_traceback = sys.exc_info()
Georg Brandlf6945182008-02-01 11:56:49 +0000413 print("*** print_tb:")
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000414 traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
Georg Brandlf6945182008-02-01 11:56:49 +0000415 print("*** print_exception:")
Matthias Bussonniercdb89cd2017-06-01 14:54:01 -0700416 # exc_type below is ignored on 3.5 and later
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000417 traceback.print_exception(exc_type, exc_value, exc_traceback,
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000418 limit=2, file=sys.stdout)
Georg Brandlf6945182008-02-01 11:56:49 +0000419 print("*** print_exc:")
Zachary Warec90fccd2016-08-10 00:35:27 -0500420 traceback.print_exc(limit=2, file=sys.stdout)
Georg Brandlf6945182008-02-01 11:56:49 +0000421 print("*** format_exc, first and last line:")
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000422 formatted_lines = traceback.format_exc().splitlines()
Georg Brandlf6945182008-02-01 11:56:49 +0000423 print(formatted_lines[0])
424 print(formatted_lines[-1])
425 print("*** format_exception:")
Matthias Bussonniercdb89cd2017-06-01 14:54:01 -0700426 # exc_type below is ignored on 3.5 and later
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000427 print(repr(traceback.format_exception(exc_type, exc_value,
428 exc_traceback)))
Georg Brandlf6945182008-02-01 11:56:49 +0000429 print("*** extract_tb:")
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000430 print(repr(traceback.extract_tb(exc_traceback)))
Georg Brandlf6945182008-02-01 11:56:49 +0000431 print("*** format_tb:")
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000432 print(repr(traceback.format_tb(exc_traceback)))
433 print("*** tb_lineno:", exc_traceback.tb_lineno)
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000434
R. David Murraye02a3012009-04-27 18:38:19 +0000435The output for the example would look similar to this:
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000436
R. David Murraye02a3012009-04-27 18:38:19 +0000437.. testoutput::
438 :options: +NORMALIZE_WHITESPACE
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000439
440 *** print_tb:
R. David Murraye02a3012009-04-27 18:38:19 +0000441 File "<doctest...>", line 10, in <module>
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000442 lumberjack()
443 *** print_exception:
444 Traceback (most recent call last):
R. David Murraye02a3012009-04-27 18:38:19 +0000445 File "<doctest...>", line 10, in <module>
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000446 lumberjack()
R. David Murraye02a3012009-04-27 18:38:19 +0000447 File "<doctest...>", line 4, in lumberjack
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000448 bright_side_of_death()
449 IndexError: tuple index out of range
450 *** print_exc:
451 Traceback (most recent call last):
R. David Murraye02a3012009-04-27 18:38:19 +0000452 File "<doctest...>", line 10, in <module>
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000453 lumberjack()
R. David Murraye02a3012009-04-27 18:38:19 +0000454 File "<doctest...>", line 4, in lumberjack
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000455 bright_side_of_death()
456 IndexError: tuple index out of range
457 *** format_exc, first and last line:
458 Traceback (most recent call last):
459 IndexError: tuple index out of range
460 *** format_exception:
461 ['Traceback (most recent call last):\n',
R. David Murraye02a3012009-04-27 18:38:19 +0000462 ' File "<doctest...>", line 10, in <module>\n lumberjack()\n',
463 ' File "<doctest...>", line 4, in lumberjack\n bright_side_of_death()\n',
464 ' File "<doctest...>", line 7, in bright_side_of_death\n return tuple()[0]\n',
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000465 'IndexError: tuple index out of range\n']
466 *** extract_tb:
Zachary Warec90fccd2016-08-10 00:35:27 -0500467 [<FrameSummary file <doctest...>, line 10 in <module>>,
468 <FrameSummary file <doctest...>, line 4 in lumberjack>,
469 <FrameSummary file <doctest...>, line 7 in bright_side_of_death>]
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000470 *** format_tb:
R. David Murraye02a3012009-04-27 18:38:19 +0000471 [' File "<doctest...>", line 10, in <module>\n lumberjack()\n',
472 ' File "<doctest...>", line 4, in lumberjack\n bright_side_of_death()\n',
473 ' File "<doctest...>", line 7, in bright_side_of_death\n return tuple()[0]\n']
474 *** tb_lineno: 10
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000475
476
477The following example shows the different ways to print and format the stack::
478
479 >>> import traceback
480 >>> def another_function():
481 ... lumberstack()
Georg Brandl48310cd2009-01-03 21:18:54 +0000482 ...
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000483 >>> def lumberstack():
484 ... traceback.print_stack()
Georg Brandlf6945182008-02-01 11:56:49 +0000485 ... print(repr(traceback.extract_stack()))
486 ... print(repr(traceback.format_stack()))
Georg Brandl48310cd2009-01-03 21:18:54 +0000487 ...
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000488 >>> another_function()
489 File "<doctest>", line 10, in <module>
490 another_function()
491 File "<doctest>", line 3, in another_function
492 lumberstack()
493 File "<doctest>", line 6, in lumberstack
494 traceback.print_stack()
495 [('<doctest>', 10, '<module>', 'another_function()'),
496 ('<doctest>', 3, 'another_function', 'lumberstack()'),
Georg Brandlf6945182008-02-01 11:56:49 +0000497 ('<doctest>', 7, 'lumberstack', 'print(repr(traceback.extract_stack()))')]
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000498 [' File "<doctest>", line 10, in <module>\n another_function()\n',
499 ' File "<doctest>", line 3, in another_function\n lumberstack()\n',
Georg Brandlf6945182008-02-01 11:56:49 +0000500 ' File "<doctest>", line 8, in lumberstack\n print(repr(traceback.format_stack()))\n']
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000501
502
R. David Murraye02a3012009-04-27 18:38:19 +0000503This last example demonstrates the final few formatting functions:
504
505.. doctest::
506 :options: +NORMALIZE_WHITESPACE
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000507
508 >>> import traceback
Georg Brandl0142d4a2009-04-27 16:22:44 +0000509 >>> traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'),
510 ... ('eggs.py', 42, 'eggs', 'return "bacon"')])
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000511 [' File "spam.py", line 3, in <module>\n spam.eggs()\n',
512 ' File "eggs.py", line 42, in eggs\n return "bacon"\n']
Georg Brandl0142d4a2009-04-27 16:22:44 +0000513 >>> an_error = IndexError('tuple index out of range')
514 >>> traceback.format_exception_only(type(an_error), an_error)
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000515 ['IndexError: tuple index out of range\n']