blob: 55d331c996a187c343196bf974b86db05022398e [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
Senthil Kumarana82908f2016-01-15 21:45:17 -080039.. function:: print_exception(etype, value, tb, limit=None, file=None, chain=True)
Georg Brandl116aa622007-08-15 14:28:22 +000040
Senthil Kumarana82908f2016-01-15 21:45:17 -080041 Print exception information and stack trace entries from traceback object
42 *tb* to *file*. This differs from :func:`print_tb` in the following
Georg Brandl1aea30a2008-07-19 15:51:07 +000043 ways:
44
Senthil Kumarana82908f2016-01-15 21:45:17 -080045 * if *tb* is not ``None``, it prints a header ``Traceback (most recent
Georg Brandl1aea30a2008-07-19 15:51:07 +000046 call last):``
Senthil Kumarana82908f2016-01-15 21:45:17 -080047 * it prints the exception *etype* and *value* after the stack trace
Matthias Bussonniercdb89cd2017-06-01 14:54:01 -070048 * if *type(value)* is :exc:`SyntaxError` and *value* has the appropriate
49 format, it prints the line where the syntax error occurred with a caret
50 indicating the approximate position of the error.
Georg Brandl1aea30a2008-07-19 15:51:07 +000051
Serhiy Storchaka24559e42015-05-03 13:19:46 +030052 The optional *limit* argument has the same meaning as for :func:`print_tb`.
Georg Brandl1aea30a2008-07-19 15:51:07 +000053 If *chain* is true (the default), then chained exceptions (the
54 :attr:`__cause__` or :attr:`__context__` attributes of the exception) will be
55 printed as well, like the interpreter itself does when printing an unhandled
56 exception.
Georg Brandl116aa622007-08-15 14:28:22 +000057
Matthias Bussonniercdb89cd2017-06-01 14:54:01 -070058 .. versionchanged:: 3.5
59 The *etype* argument is ignored and inferred from the type of *value*.
60
Georg Brandl116aa622007-08-15 14:28:22 +000061
Georg Brandl7f01a132009-09-16 15:58:14 +000062.. function:: print_exc(limit=None, file=None, chain=True)
Georg Brandl116aa622007-08-15 14:28:22 +000063
Serhiy Storchaka24559e42015-05-03 13:19:46 +030064 This is a shorthand for ``print_exception(*sys.exc_info(), limit, file,
65 chain)``.
Georg Brandl116aa622007-08-15 14:28:22 +000066
67
Georg Brandl7f01a132009-09-16 15:58:14 +000068.. function:: print_last(limit=None, file=None, chain=True)
Georg Brandl116aa622007-08-15 14:28:22 +000069
70 This is a shorthand for ``print_exception(sys.last_type, sys.last_value,
Serhiy Storchaka24559e42015-05-03 13:19:46 +030071 sys.last_traceback, limit, file, chain)``. In general it will work only
72 after an exception has reached an interactive prompt (see
73 :data:`sys.last_type`).
Georg Brandl116aa622007-08-15 14:28:22 +000074
75
Georg Brandl7f01a132009-09-16 15:58:14 +000076.. function:: print_stack(f=None, limit=None, file=None)
Georg Brandl116aa622007-08-15 14:28:22 +000077
Serhiy Storchaka24559e42015-05-03 13:19:46 +030078 Print up to *limit* stack trace entries (starting from the invocation
79 point) if *limit* is positive. Otherwise, print the last ``abs(limit)``
80 entries. If *limit* is omitted or ``None``, all entries are printed.
81 The optional *f* argument can be used to specify an alternate stack frame
82 to start. The optional *file* argument has the same meaning as for
83 :func:`print_tb`.
84
85 .. versionchanged:: 3.5
86 Added negative *limit* support.
Georg Brandl116aa622007-08-15 14:28:22 +000087
88
Senthil Kumarana82908f2016-01-15 21:45:17 -080089.. function:: extract_tb(tb, limit=None)
Georg Brandl116aa622007-08-15 14:28:22 +000090
Serhiy Storchaka24559e42015-05-03 13:19:46 +030091 Return a list of "pre-processed" stack trace entries extracted from the
Senthil Kumarana82908f2016-01-15 21:45:17 -080092 traceback object *tb*. It is useful for alternate formatting of
Serhiy Storchaka24559e42015-05-03 13:19:46 +030093 stack traces. The optional *limit* argument has the same meaning as for
94 :func:`print_tb`. A "pre-processed" stack trace entry is a 4-tuple
95 (*filename*, *line number*, *function name*, *text*) representing the
96 information that is usually printed for a stack trace. The *text* is a
97 string with leading and trailing whitespace stripped; if the source is
98 not available it is ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +000099
100
Georg Brandl7f01a132009-09-16 15:58:14 +0000101.. function:: extract_stack(f=None, limit=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000102
103 Extract the raw traceback from the current stack frame. The return value has
104 the same format as for :func:`extract_tb`. The optional *f* and *limit*
105 arguments have the same meaning as for :func:`print_stack`.
106
107
Senthil Kumarana82908f2016-01-15 21:45:17 -0800108.. function:: format_list(extracted_list)
Georg Brandl116aa622007-08-15 14:28:22 +0000109
110 Given a list of tuples as returned by :func:`extract_tb` or
Senthil Kumarana82908f2016-01-15 21:45:17 -0800111 :func:`extract_stack`, return a list of strings ready for printing. Each
112 string in the resulting list corresponds to the item with the same index in
113 the argument list. Each string ends in a newline; the strings may contain
114 internal newlines as well, for those items whose source text line is not
115 ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000116
117
Senthil Kumarana82908f2016-01-15 21:45:17 -0800118.. function:: format_exception_only(etype, value)
Georg Brandl116aa622007-08-15 14:28:22 +0000119
Senthil Kumarana82908f2016-01-15 21:45:17 -0800120 Format the exception part of a traceback. The arguments are the exception
121 type and value such as given by ``sys.last_type`` and ``sys.last_value``.
122 The return value is a list of strings, each ending in a newline. Normally,
123 the list contains a single string; however, for :exc:`SyntaxError`
124 exceptions, it contains several lines that (when printed) display detailed
125 information about where the syntax error occurred. The message indicating
126 which exception occurred is the always last string in the list.
Georg Brandl116aa622007-08-15 14:28:22 +0000127
128
Senthil Kumarana82908f2016-01-15 21:45:17 -0800129.. function:: format_exception(etype, value, tb, limit=None, chain=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000130
131 Format a stack trace and the exception information. The arguments have the
132 same meaning as the corresponding arguments to :func:`print_exception`. The
Senthil Kumarana82908f2016-01-15 21:45:17 -0800133 return value is a list of strings, each ending in a newline and some
134 containing internal newlines. When these lines are concatenated and printed,
135 exactly the same text is printed as does :func:`print_exception`.
Georg Brandl116aa622007-08-15 14:28:22 +0000136
Matthias Bussonniercdb89cd2017-06-01 14:54:01 -0700137 .. versionchanged:: 3.5
138 The *etype* argument is ignored and inferred from the type of *value*.
139
Georg Brandl116aa622007-08-15 14:28:22 +0000140
Georg Brandl7f01a132009-09-16 15:58:14 +0000141.. function:: format_exc(limit=None, chain=True)
Georg Brandl1aea30a2008-07-19 15:51:07 +0000142
Senthil Kumarana82908f2016-01-15 21:45:17 -0800143 This is like ``print_exc(limit)`` but returns a string instead of printing to
144 a file.
Georg Brandl1aea30a2008-07-19 15:51:07 +0000145
146
Georg Brandl7f01a132009-09-16 15:58:14 +0000147.. function:: format_tb(tb, limit=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000148
149 A shorthand for ``format_list(extract_tb(tb, limit))``.
150
151
Georg Brandl7f01a132009-09-16 15:58:14 +0000152.. function:: format_stack(f=None, limit=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000153
154 A shorthand for ``format_list(extract_stack(f, limit))``.
155
Andrew Kuchling173a1572013-09-15 18:15:56 -0400156.. function:: clear_frames(tb)
157
158 Clears the local variables of all the stack frames in a traceback *tb*
159 by calling the :meth:`clear` method of each frame object.
160
161 .. versionadded:: 3.4
162
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300163.. function:: walk_stack(f)
164
Berker Peksag49f373b2015-03-06 12:18:06 +0200165 Walk a stack following ``f.f_back`` from the given frame, yielding the frame
166 and line number for each frame. If *f* is ``None``, the current stack is
167 used. This helper is used with :meth:`StackSummary.extract`.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300168
169 .. versionadded:: 3.5
170
171.. function:: walk_tb(tb)
172
Berker Peksag49f373b2015-03-06 12:18:06 +0200173 Walk a traceback following ``tb_next`` yielding the frame and line number
174 for each frame. This helper is used with :meth:`StackSummary.extract`.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300175
176 .. versionadded:: 3.5
177
178The module also defines the following classes:
179
180:class:`TracebackException` Objects
181-----------------------------------
182
Berker Peksag49f373b2015-03-06 12:18:06 +0200183.. versionadded:: 3.5
184
185:class:`TracebackException` objects are created from actual exceptions to
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300186capture data for later printing in a lightweight fashion.
187
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300188.. class:: TracebackException(exc_type, exc_value, exc_traceback, *, limit=None, lookup_lines=True, capture_locals=False)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300189
Berker Peksag49f373b2015-03-06 12:18:06 +0200190 Capture an exception for later rendering. *limit*, *lookup_lines* and
191 *capture_locals* are as for the :class:`StackSummary` class.
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300192
193 Note that when locals are captured, they are also shown in the traceback.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300194
Berker Peksag49f373b2015-03-06 12:18:06 +0200195 .. attribute:: __cause__
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300196
Berker Peksag49f373b2015-03-06 12:18:06 +0200197 A :class:`TracebackException` of the original ``__cause__``.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300198
Berker Peksag49f373b2015-03-06 12:18:06 +0200199 .. attribute:: __context__
Robert Collinsd7c7e0e2015-03-05 20:28:52 +1300200
Berker Peksag49f373b2015-03-06 12:18:06 +0200201 A :class:`TracebackException` of the original ``__context__``.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300202
Berker Peksag49f373b2015-03-06 12:18:06 +0200203 .. attribute:: __suppress_context__
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300204
Berker Peksag49f373b2015-03-06 12:18:06 +0200205 The ``__suppress_context__`` value from the original exception.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300206
Berker Peksag49f373b2015-03-06 12:18:06 +0200207 .. attribute:: stack
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300208
Berker Peksag49f373b2015-03-06 12:18:06 +0200209 A :class:`StackSummary` representing the traceback.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300210
Berker Peksag49f373b2015-03-06 12:18:06 +0200211 .. attribute:: exc_type
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300212
Berker Peksag49f373b2015-03-06 12:18:06 +0200213 The class of the original traceback.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300214
Berker Peksag49f373b2015-03-06 12:18:06 +0200215 .. attribute:: filename
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300216
Berker Peksag49f373b2015-03-06 12:18:06 +0200217 For syntax errors - the file name where the error occurred.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300218
Berker Peksag49f373b2015-03-06 12:18:06 +0200219 .. attribute:: lineno
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300220
Berker Peksag49f373b2015-03-06 12:18:06 +0200221 For syntax errors - the line number where the error occurred.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300222
Berker Peksag49f373b2015-03-06 12:18:06 +0200223 .. attribute:: text
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300224
Berker Peksag49f373b2015-03-06 12:18:06 +0200225 For syntax errors - the text where the error occurred.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300226
Berker Peksag49f373b2015-03-06 12:18:06 +0200227 .. attribute:: offset
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300228
Berker Peksag49f373b2015-03-06 12:18:06 +0200229 For syntax errors - the offset into the text where the error occurred.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300230
Berker Peksag49f373b2015-03-06 12:18:06 +0200231 .. attribute:: msg
232
233 For syntax errors - the compiler error message.
234
235 .. classmethod:: from_exception(exc, *, limit=None, lookup_lines=True, capture_locals=False)
236
237 Capture an exception for later rendering. *limit*, *lookup_lines* and
238 *capture_locals* are as for the :class:`StackSummary` class.
239
240 Note that when locals are captured, they are also shown in the traceback.
241
242 .. method:: format(*, chain=True)
243
244 Format the exception.
245
246 If *chain* is not ``True``, ``__cause__`` and ``__context__`` will not
247 be formatted.
248
249 The return value is a generator of strings, each ending in a newline and
250 some containing internal newlines. :func:`~traceback.print_exception`
251 is a wrapper around this method which just prints the lines to a file.
252
253 The message indicating which exception occurred is always the last
254 string in the output.
255
256 .. method:: format_exception_only()
257
258 Format the exception part of the traceback.
259
260 The return value is a generator of strings, each ending in a newline.
261
262 Normally, the generator emits a single string; however, for
263 :exc:`SyntaxError` exceptions, it emits several lines that (when
264 printed) display detailed information about where the syntax
265 error occurred.
266
267 The message indicating which exception occurred is always the last
268 string in the output.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300269
270
271:class:`StackSummary` Objects
272-----------------------------
273
Berker Peksag49f373b2015-03-06 12:18:06 +0200274.. versionadded:: 3.5
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300275
Berker Peksag49f373b2015-03-06 12:18:06 +0200276:class:`StackSummary` objects represent a call stack ready for formatting.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300277
Berker Peksag49f373b2015-03-06 12:18:06 +0200278.. class:: StackSummary
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300279
Berker Peksag49f373b2015-03-06 12:18:06 +0200280 .. classmethod:: extract(frame_gen, *, limit=None, lookup_lines=True, capture_locals=False)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300281
Berker Peksag49f373b2015-03-06 12:18:06 +0200282 Construct a :class:`StackSummary` object from a frame generator (such as
283 is returned by :func:`~traceback.walk_stack` or
284 :func:`~traceback.walk_tb`).
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300285
Berker Peksag49f373b2015-03-06 12:18:06 +0200286 If *limit* is supplied, only this many frames are taken from *frame_gen*.
287 If *lookup_lines* is ``False``, the returned :class:`FrameSummary`
288 objects will not have read their lines in yet, making the cost of
289 creating the :class:`StackSummary` cheaper (which may be valuable if it
290 may not actually get formatted). If *capture_locals* is ``True`` the
291 local variables in each :class:`FrameSummary` are captured as object
292 representations.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300293
Berker Peksag49f373b2015-03-06 12:18:06 +0200294 .. classmethod:: from_list(a_list)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300295
Berker Peksag49f373b2015-03-06 12:18:06 +0200296 Construct a :class:`StackSummary` object from a supplied old-style list
297 of tuples. Each tuple should be a 4-tuple with filename, lineno, name,
298 line as the elements.
299
Nick Coghland0034232016-08-15 13:11:34 +1000300 .. method:: format()
301
302 Returns a list of strings ready for printing. Each string in the
303 resulting list corresponds to a single frame from the stack.
304 Each string ends in a newline; the strings may contain internal
305 newlines as well, for those items with source text lines.
306
307 For long sequences of the same frame and line, the first few
308 repetitions are shown, followed by a summary line stating the exact
309 number of further repetitions.
310
Nick Coghlan02d03df2016-08-16 10:58:14 +1000311 .. versionchanged:: 3.6
312 Long sequences of repeated frames are now abbreviated.
Nick Coghland0034232016-08-15 13:11:34 +1000313
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300314
315:class:`FrameSummary` Objects
316-----------------------------
317
Berker Peksag49f373b2015-03-06 12:18:06 +0200318.. versionadded:: 3.5
319
320:class:`FrameSummary` objects represent a single frame in a traceback.
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300321
322.. class:: FrameSummary(filename, lineno, name, lookup_line=True, locals=None, line=None)
Robert Collins6bc2c1e2015-03-05 12:07:57 +1300323
324 Represent a single frame in the traceback or stack that is being formatted
325 or printed. It may optionally have a stringified version of the frames
Berker Peksag49f373b2015-03-06 12:18:06 +0200326 locals included in it. If *lookup_line* is ``False``, the source code is not
327 looked up until the :class:`FrameSummary` has the :attr:`~FrameSummary.line`
328 attribute accessed (which also happens when casting it to a tuple).
329 :attr:`~FrameSummary.line` may be directly provided, and will prevent line
330 lookups happening at all. *locals* is an optional local variable
331 dictionary, and if supplied the variable representations are stored in the
332 summary for later display.
Georg Brandl116aa622007-08-15 14:28:22 +0000333
Georg Brandl116aa622007-08-15 14:28:22 +0000334.. _traceback-example:
335
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000336Traceback Examples
337------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000338
339This simple example implements a basic read-eval-print loop, similar to (but
340less useful than) the standard Python interactive interpreter loop. For a more
341complete implementation of the interpreter loop, refer to the :mod:`code`
342module. ::
343
344 import sys, traceback
345
346 def run_user_code(envdir):
Georg Brandl8d5c3922007-12-02 22:48:17 +0000347 source = input(">>> ")
Georg Brandl116aa622007-08-15 14:28:22 +0000348 try:
349 exec(source, envdir)
Andrew Svetlov47395612012-11-02 22:07:26 +0200350 except Exception:
Collin Winterc79461b2007-09-01 23:34:30 +0000351 print("Exception in user code:")
352 print("-"*60)
Georg Brandl116aa622007-08-15 14:28:22 +0000353 traceback.print_exc(file=sys.stdout)
Collin Winterc79461b2007-09-01 23:34:30 +0000354 print("-"*60)
Georg Brandl116aa622007-08-15 14:28:22 +0000355
356 envdir = {}
Collin Winterc79461b2007-09-01 23:34:30 +0000357 while True:
Georg Brandl116aa622007-08-15 14:28:22 +0000358 run_user_code(envdir)
359
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000360
361The following example demonstrates the different ways to print and format the
R. David Murraye02a3012009-04-27 18:38:19 +0000362exception and traceback:
363
364.. testcode::
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000365
366 import sys, traceback
367
368 def lumberjack():
369 bright_side_of_death()
Georg Brandl48310cd2009-01-03 21:18:54 +0000370
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000371 def bright_side_of_death():
372 return tuple()[0]
Georg Brandl48310cd2009-01-03 21:18:54 +0000373
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000374 try:
375 lumberjack()
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000376 except IndexError:
377 exc_type, exc_value, exc_traceback = sys.exc_info()
Georg Brandlf6945182008-02-01 11:56:49 +0000378 print("*** print_tb:")
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000379 traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
Georg Brandlf6945182008-02-01 11:56:49 +0000380 print("*** print_exception:")
Matthias Bussonniercdb89cd2017-06-01 14:54:01 -0700381 # exc_type below is ignored on 3.5 and later
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000382 traceback.print_exception(exc_type, exc_value, exc_traceback,
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000383 limit=2, file=sys.stdout)
Georg Brandlf6945182008-02-01 11:56:49 +0000384 print("*** print_exc:")
Zachary Warec90fccd2016-08-10 00:35:27 -0500385 traceback.print_exc(limit=2, file=sys.stdout)
Georg Brandlf6945182008-02-01 11:56:49 +0000386 print("*** format_exc, first and last line:")
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000387 formatted_lines = traceback.format_exc().splitlines()
Georg Brandlf6945182008-02-01 11:56:49 +0000388 print(formatted_lines[0])
389 print(formatted_lines[-1])
390 print("*** format_exception:")
Matthias Bussonniercdb89cd2017-06-01 14:54:01 -0700391 # exc_type below is ignored on 3.5 and later
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000392 print(repr(traceback.format_exception(exc_type, exc_value,
393 exc_traceback)))
Georg Brandlf6945182008-02-01 11:56:49 +0000394 print("*** extract_tb:")
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000395 print(repr(traceback.extract_tb(exc_traceback)))
Georg Brandlf6945182008-02-01 11:56:49 +0000396 print("*** format_tb:")
Ezio Melotti5e0110e2010-03-13 01:28:34 +0000397 print(repr(traceback.format_tb(exc_traceback)))
398 print("*** tb_lineno:", exc_traceback.tb_lineno)
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000399
R. David Murraye02a3012009-04-27 18:38:19 +0000400The output for the example would look similar to this:
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000401
R. David Murraye02a3012009-04-27 18:38:19 +0000402.. testoutput::
403 :options: +NORMALIZE_WHITESPACE
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000404
405 *** print_tb:
R. David Murraye02a3012009-04-27 18:38:19 +0000406 File "<doctest...>", line 10, in <module>
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000407 lumberjack()
408 *** print_exception:
409 Traceback (most recent call last):
R. David Murraye02a3012009-04-27 18:38:19 +0000410 File "<doctest...>", line 10, in <module>
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000411 lumberjack()
R. David Murraye02a3012009-04-27 18:38:19 +0000412 File "<doctest...>", line 4, in lumberjack
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000413 bright_side_of_death()
414 IndexError: tuple index out of range
415 *** print_exc:
416 Traceback (most recent call last):
R. David Murraye02a3012009-04-27 18:38:19 +0000417 File "<doctest...>", line 10, in <module>
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000418 lumberjack()
R. David Murraye02a3012009-04-27 18:38:19 +0000419 File "<doctest...>", line 4, in lumberjack
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000420 bright_side_of_death()
421 IndexError: tuple index out of range
422 *** format_exc, first and last line:
423 Traceback (most recent call last):
424 IndexError: tuple index out of range
425 *** format_exception:
426 ['Traceback (most recent call last):\n',
R. David Murraye02a3012009-04-27 18:38:19 +0000427 ' File "<doctest...>", line 10, in <module>\n lumberjack()\n',
428 ' File "<doctest...>", line 4, in lumberjack\n bright_side_of_death()\n',
429 ' File "<doctest...>", line 7, in bright_side_of_death\n return tuple()[0]\n',
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000430 'IndexError: tuple index out of range\n']
431 *** extract_tb:
Zachary Warec90fccd2016-08-10 00:35:27 -0500432 [<FrameSummary file <doctest...>, line 10 in <module>>,
433 <FrameSummary file <doctest...>, line 4 in lumberjack>,
434 <FrameSummary file <doctest...>, line 7 in bright_side_of_death>]
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000435 *** format_tb:
R. David Murraye02a3012009-04-27 18:38:19 +0000436 [' File "<doctest...>", line 10, in <module>\n lumberjack()\n',
437 ' File "<doctest...>", line 4, in lumberjack\n bright_side_of_death()\n',
438 ' File "<doctest...>", line 7, in bright_side_of_death\n return tuple()[0]\n']
439 *** tb_lineno: 10
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000440
441
442The following example shows the different ways to print and format the stack::
443
444 >>> import traceback
445 >>> def another_function():
446 ... lumberstack()
Georg Brandl48310cd2009-01-03 21:18:54 +0000447 ...
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000448 >>> def lumberstack():
449 ... traceback.print_stack()
Georg Brandlf6945182008-02-01 11:56:49 +0000450 ... print(repr(traceback.extract_stack()))
451 ... print(repr(traceback.format_stack()))
Georg Brandl48310cd2009-01-03 21:18:54 +0000452 ...
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000453 >>> another_function()
454 File "<doctest>", line 10, in <module>
455 another_function()
456 File "<doctest>", line 3, in another_function
457 lumberstack()
458 File "<doctest>", line 6, in lumberstack
459 traceback.print_stack()
460 [('<doctest>', 10, '<module>', 'another_function()'),
461 ('<doctest>', 3, 'another_function', 'lumberstack()'),
Georg Brandlf6945182008-02-01 11:56:49 +0000462 ('<doctest>', 7, 'lumberstack', 'print(repr(traceback.extract_stack()))')]
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000463 [' File "<doctest>", line 10, in <module>\n another_function()\n',
464 ' File "<doctest>", line 3, in another_function\n lumberstack()\n',
Georg Brandlf6945182008-02-01 11:56:49 +0000465 ' File "<doctest>", line 8, in lumberstack\n print(repr(traceback.format_stack()))\n']
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000466
467
R. David Murraye02a3012009-04-27 18:38:19 +0000468This last example demonstrates the final few formatting functions:
469
470.. doctest::
471 :options: +NORMALIZE_WHITESPACE
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000472
473 >>> import traceback
Georg Brandl0142d4a2009-04-27 16:22:44 +0000474 >>> traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'),
475 ... ('eggs.py', 42, 'eggs', 'return "bacon"')])
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000476 [' File "spam.py", line 3, in <module>\n spam.eggs()\n',
477 ' File "eggs.py", line 42, in eggs\n return "bacon"\n']
Georg Brandl0142d4a2009-04-27 16:22:44 +0000478 >>> an_error = IndexError('tuple index out of range')
479 >>> traceback.format_exception_only(type(an_error), an_error)
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000480 ['IndexError: tuple index out of range\n']