Debian Codegraph @

Doc/library/traceback.rst

raw
1 :mod:`!traceback` --- Print or retrieve a stack traceback
2 =========================================================
3
4 .. module:: traceback
5 :synopsis: Print or retrieve a stack traceback.
6
7 **Source code:** :source:`Lib/traceback.py`
8
9 --------------
10
11 This module provides a standard interface to extract, format and print
12 stack traces of Python programs. It is more flexible than the
13 interpreter's default traceback display, and therefore makes it
14 possible to configure certain aspects of the output. Finally,
15 it contains a utility for capturing enough information about an
16 exception to print it later, without the need to save a reference
17 to the actual exception. Since exceptions can be the roots of large
18 objects graph, this utility can significantly improve
19 memory management.
20
21 .. index:: pair: object; traceback
22
23 The module uses :ref:`traceback objects <traceback-objects>` --- these are
24 objects of type :class:`types.TracebackType`,
25 which are assigned to the :attr:`~BaseException.__traceback__` field of
26 :class:`BaseException` instances.
27
28 .. seealso::
29
30 Module :mod:`faulthandler`
31 Used to dump Python tracebacks explicitly, on a fault, after a timeout, or on a user signal.
32
33 Module :mod:`pdb`
34 Interactive source code debugger for Python programs.
35
36 The module's API can be divided into two parts:
37
38 * Module-level functions offering basic functionality, which are useful for interactive
39 inspection of exceptions and tracebacks.
40
41 * :class:`TracebackException` class and its helper classes
42 :class:`StackSummary` and :class:`FrameSummary`. These offer both more
43 flexibility in the output generated and the ability to store the information
44 necessary for later formatting without holding references to actual exception
45 and traceback objects.
46
47 .. versionadded:: 3.13
48 Output is colorized by default and can be
49 :ref:`controlled using environment variables <using-on-controlling-color>`.
50
51
52 Module-Level Functions
53 ----------------------
54
55 .. function:: print_tb(tb, limit=None, file=None)
56
57 Print up to *limit* stack trace entries from
58 :ref:`traceback object <traceback-objects>` *tb* (starting
59 from the caller's frame) if *limit* is positive. Otherwise, print the last
60 ``abs(limit)`` entries. If *limit* is omitted or ``None``, all entries are
61 printed. If *file* is omitted or ``None``, the output goes to
62 :data:`sys.stderr`; otherwise it should be an open
63 :term:`file <file object>` or :term:`file-like object` to
64 receive the output.
65
66 .. note::
67
68 The meaning of the *limit* parameter is different than the meaning
69 of :const:`sys.tracebacklimit`. A negative *limit* value corresponds to
70 a positive value of :const:`!sys.tracebacklimit`, whereas the behaviour of
71 a positive *limit* value cannot be achieved with
72 :const:`!sys.tracebacklimit`.
73
74 .. versionchanged:: 3.5
75 Added negative *limit* support.
76
77
78 .. function:: print_exception(exc, /[, value, tb], limit=None, \
79 file=None, chain=True)
80
81 Print exception information and stack trace entries from
82 :ref:`traceback object <traceback-objects>`
83 *tb* to *file*. This differs from :func:`print_tb` in the following
84 ways:
85
86 * if *tb* is not ``None``, it prints a header ``Traceback (most recent
87 call last):``
88
89 * it prints the exception type and *value* after the stack trace
90
91 .. index:: single: ^ (caret); marker
92
93 * if *type(value)* is :exc:`SyntaxError` and *value* has the appropriate
94 format, it prints the line where the syntax error occurred with a caret
95 indicating the approximate position of the error.
96
97 Since Python 3.10, instead of passing *value* and *tb*, an exception object
98 can be passed as the first argument. If *value* and *tb* are provided, the
99 first argument is ignored in order to provide backwards compatibility.
100
101 The optional *limit* argument has the same meaning as for :func:`print_tb`.
102 If *chain* is true (the default), then chained exceptions (the
103 :attr:`~BaseException.__cause__` or :attr:`~BaseException.__context__`
104 attributes of the exception) will be
105 printed as well, like the interpreter itself does when printing an unhandled
106 exception.
107
108 .. versionchanged:: 3.5
109 The *etype* argument is ignored and inferred from the type of *value*.
110
111 .. versionchanged:: 3.10
112 The *etype* parameter has been renamed to *exc* and is now
113 positional-only.
114
115
116 .. function:: print_exc(limit=None, file=None, chain=True)
117
118 This is a shorthand for ``print_exception(sys.exception(), limit=limit, file=file,
119 chain=chain)``.
120
121
122 .. function:: print_last(limit=None, file=None, chain=True)
123
124 This is a shorthand for ``print_exception(sys.last_exc, limit=limit, file=file,
125 chain=chain)``. In general it will work only after an exception has reached
126 an interactive prompt (see :data:`sys.last_exc`).
127
128
129 .. function:: print_stack(f=None, limit=None, file=None)
130
131 Print up to *limit* stack trace entries (starting from the invocation
132 point) if *limit* is positive. Otherwise, print the last ``abs(limit)``
133 entries. If *limit* is omitted or ``None``, all entries are printed.
134 The optional *f* argument can be used to specify an alternate
135 :ref:`stack frame <frame-objects>`
136 to start. The optional *file* argument has the same meaning as for
137 :func:`print_tb`.
138
139 .. versionchanged:: 3.5
140 Added negative *limit* support.
141
142
143 .. function:: extract_tb(tb, limit=None)
144
145 Return a :class:`StackSummary` object representing a list of "pre-processed"
146 stack trace entries extracted from the
147 :ref:`traceback object <traceback-objects>` *tb*. It is useful
148 for alternate formatting of stack traces. The optional *limit* argument has
149 the same meaning as for :func:`print_tb`. A "pre-processed" stack trace
150 entry is a :class:`FrameSummary` object containing attributes
151 :attr:`~FrameSummary.filename`, :attr:`~FrameSummary.lineno`,
152 :attr:`~FrameSummary.name`, and :attr:`~FrameSummary.line` representing the
153 information that is usually printed for a stack trace.
154
155
156 .. function:: extract_stack(f=None, limit=None)
157
158 Extract the raw traceback from the current
159 :ref:`stack frame <frame-objects>`. The return value has
160 the same format as for :func:`extract_tb`. The optional *f* and *limit*
161 arguments have the same meaning as for :func:`print_stack`.
162
163
164 .. function:: print_list(extracted_list, file=None)
165
166 Print the list of tuples as returned by :func:`extract_tb` or
167 :func:`extract_stack` as a formatted stack trace to the given file.
168 If *file* is ``None``, the output is written to :data:`sys.stderr`.
169
170
171 .. function:: format_list(extracted_list)
172
173 Given a list of tuples or :class:`FrameSummary` objects as returned by
174 :func:`extract_tb` or :func:`extract_stack`, return a list of strings ready
175 for printing. Each string in the resulting list corresponds to the item with
176 the same index in the argument list. Each string ends in a newline; the
177 strings may contain internal newlines as well, for those items whose source
178 text line is not ``None``.
179
180
181 .. function:: format_exception_only(exc, /[, value], *, show_group=False)
182
183 Format the exception part of a traceback using an exception value such as
184 given by :data:`sys.last_value`. The return value is a list of strings, each
185 ending in a newline. The list contains the exception's message, which is
186 normally a single string; however, for :exc:`SyntaxError` exceptions, it
187 contains several lines that (when printed) display detailed information
188 about where the syntax error occurred. Following the message, the list
189 contains the exception's :attr:`notes <BaseException.__notes__>`.
190
191 Since Python 3.10, instead of passing *value*, an exception object
192 can be passed as the first argument. If *value* is provided, the first
193 argument is ignored in order to provide backwards compatibility.
194
195 When *show_group* is ``True``, and the exception is an instance of
196 :exc:`BaseExceptionGroup`, the nested exceptions are included as
197 well, recursively, with indentation relative to their nesting depth.
198
199 .. versionchanged:: 3.10
200 The *etype* parameter has been renamed to *exc* and is now
201 positional-only.
202
203 .. versionchanged:: 3.11
204 The returned list now includes any
205 :attr:`notes <BaseException.__notes__>` attached to the exception.
206
207 .. versionchanged:: 3.13
208 *show_group* parameter was added.
209
210
211 .. function:: format_exception(exc, /[, value, tb], limit=None, chain=True)
212
213 Format a stack trace and the exception information. The arguments have the
214 same meaning as the corresponding arguments to :func:`print_exception`. The
215 return value is a list of strings, each ending in a newline and some
216 containing internal newlines. When these lines are concatenated and printed,
217 exactly the same text is printed as does :func:`print_exception`.
218
219 .. versionchanged:: 3.5
220 The *etype* argument is ignored and inferred from the type of *value*.
221
222 .. versionchanged:: 3.10
223 This function's behavior and signature were modified to match
224 :func:`print_exception`.
225
226
227 .. function:: format_exc(limit=None, chain=True)
228
229 This is like ``print_exc(limit)`` but returns a string instead of printing to
230 a file.
231
232
233 .. function:: format_tb(tb, limit=None)
234
235 A shorthand for ``format_list(extract_tb(tb, limit))``.
236
237
238 .. function:: format_stack(f=None, limit=None)
239
240 A shorthand for ``format_list(extract_stack(f, limit))``.
241
242 .. function:: clear_frames(tb)
243
244 Clears the local variables of all the stack frames in a
245 :ref:`traceback <traceback-objects>` *tb*
246 by calling the :meth:`~frame.clear` method of each
247 :ref:`frame object <frame-objects>`.
248
249 .. versionadded:: 3.4
250
251 .. function:: walk_stack(f)
252
253 Walk a stack following :attr:`f.f_back <frame.f_back>` from the given frame,
254 yielding the frame
255 and line number for each frame. If *f* is ``None``, the current stack is
256 used. This helper is used with :meth:`StackSummary.extract`.
257
258 .. versionadded:: 3.5
259
260 .. versionchanged:: 3.14
261 This function previously returned a generator that would walk the stack
262 when first iterated over. The generator returned now is the state of the
263 stack when ``walk_stack`` is called.
264
265 .. function:: walk_tb(tb)
266
267 Walk a traceback following :attr:`~traceback.tb_next` yielding the frame and
268 line number
269 for each frame. This helper is used with :meth:`StackSummary.extract`.
270
271 .. versionadded:: 3.5
272
273
274 :class:`!TracebackException` Objects
275 ------------------------------------
276
277 .. versionadded:: 3.5
278
279 :class:`!TracebackException` objects are created from actual exceptions to
280 capture data for later printing. They offer a more lightweight method of
281 storing this information by avoiding holding references to
282 :ref:`traceback<traceback-objects>` and :ref:`frame<frame-objects>` objects.
283 In addition, they expose more options to configure the output compared to
284 the module-level functions described above.
285
286 .. class:: TracebackException(exc_type, exc_value, exc_traceback, *, limit=None, lookup_lines=True, capture_locals=False, compact=False, max_group_width=15, max_group_depth=10)
287
288 Capture an exception for later rendering. The meaning of *limit*,
289 *lookup_lines* and *capture_locals* are as for the :class:`StackSummary`
290 class.
291
292 If *compact* is true, only data that is required by
293 :class:`!TracebackException`'s :meth:`format` method
294 is saved in the class attributes. In particular, the
295 :attr:`__context__` field is calculated only if :attr:`__cause__` is
296 ``None`` and :attr:`__suppress_context__` is false.
297
298 Note that when locals are captured, they are also shown in the traceback.
299
300 *max_group_width* and *max_group_depth* control the formatting of exception
301 groups (see :exc:`BaseExceptionGroup`). The depth refers to the nesting
302 level of the group, and the width refers to the size of a single exception
303 group's exceptions array. The formatted output is truncated when either
304 limit is exceeded.
305
306 .. versionchanged:: 3.10
307 Added the *compact* parameter.
308
309 .. versionchanged:: 3.11
310 Added the *max_group_width* and *max_group_depth* parameters.
311
312 .. attribute:: __cause__
313
314 A :class:`!TracebackException` of the original
315 :attr:`~BaseException.__cause__`.
316
317 .. attribute:: __context__
318
319 A :class:`!TracebackException` of the original
320 :attr:`~BaseException.__context__`.
321
322 .. attribute:: exceptions
323
324 If ``self`` represents an :exc:`ExceptionGroup`, this field holds a list of
325 :class:`!TracebackException` instances representing the nested exceptions.
326 Otherwise it is ``None``.
327
328 .. versionadded:: 3.11
329
330 .. attribute:: __suppress_context__
331
332 The :attr:`~BaseException.__suppress_context__` value from the original
333 exception.
334
335 .. attribute:: __notes__
336
337 The :attr:`~BaseException.__notes__` value from the original exception,
338 or ``None``
339 if the exception does not have any notes. If it is not ``None``
340 is it formatted in the traceback after the exception string.
341
342 .. versionadded:: 3.11
343
344 .. attribute:: stack
345
346 A :class:`StackSummary` representing the traceback.
347
348 .. attribute:: exc_type
349
350 The class of the original traceback.
351
352 .. deprecated:: 3.13
353
354 .. attribute:: exc_type_str
355
356 String display of the class of the original exception.
357
358 .. versionadded:: 3.13
359
360 .. attribute:: filename
361
362 For syntax errors - the file name where the error occurred.
363
364 .. attribute:: lineno
365
366 For syntax errors - the line number where the error occurred.
367
368 .. attribute:: end_lineno
369
370 For syntax errors - the end line number where the error occurred.
371 Can be ``None`` if not present.
372
373 .. versionadded:: 3.10
374
375 .. attribute:: text
376
377 For syntax errors - the text where the error occurred.
378
379 .. attribute:: offset
380
381 For syntax errors - the offset into the text where the error occurred.
382
383 .. attribute:: end_offset
384
385 For syntax errors - the end offset into the text where the error occurred.
386 Can be ``None`` if not present.
387
388 .. versionadded:: 3.10
389
390 .. attribute:: msg
391
392 For syntax errors - the compiler error message.
393
394 .. classmethod:: from_exception(exc, *, limit=None, lookup_lines=True, capture_locals=False)
395
396 Capture an exception for later rendering. *limit*, *lookup_lines* and
397 *capture_locals* are as for the :class:`StackSummary` class.
398
399 Note that when locals are captured, they are also shown in the traceback.
400
401 .. method:: print(*, file=None, chain=True)
402
403 Print to *file* (default ``sys.stderr``) the exception information returned by
404 :meth:`format`.
405
406 .. versionadded:: 3.11
407
408 .. method:: format(*, chain=True)
409
410 Format the exception.
411
412 If *chain* is not ``True``, :attr:`__cause__` and :attr:`__context__`
413 will not be formatted.
414
415 The return value is a generator of strings, each ending in a newline and
416 some containing internal newlines. :func:`~traceback.print_exception`
417 is a wrapper around this method which just prints the lines to a file.
418
419 .. method:: format_exception_only(*, show_group=False)
420
421 Format the exception part of the traceback.
422
423 The return value is a generator of strings, each ending in a newline.
424
425 When *show_group* is ``False``, the generator emits the exception's
426 message followed by its notes (if it has any). The exception message
427 is normally a single string; however, for :exc:`SyntaxError` exceptions,
428 it consists of several lines that (when printed) display detailed
429 information about where the syntax error occurred.
430
431 When *show_group* is ``True``, and the exception is an instance of
432 :exc:`BaseExceptionGroup`, the nested exceptions are included as
433 well, recursively, with indentation relative to their nesting depth.
434
435 .. versionchanged:: 3.11
436 The exception's :attr:`notes <BaseException.__notes__>` are now
437 included in the output.
438
439 .. versionchanged:: 3.13
440 Added the *show_group* parameter.
441
442
443 :class:`!StackSummary` Objects
444 ------------------------------
445
446 .. versionadded:: 3.5
447
448 :class:`!StackSummary` objects represent a call stack ready for formatting.
449
450 .. class:: StackSummary
451
452 .. classmethod:: extract(frame_gen, *, limit=None, lookup_lines=True, capture_locals=False)
453
454 Construct a :class:`!StackSummary` object from a frame generator (such as
455 is returned by :func:`~traceback.walk_stack` or
456 :func:`~traceback.walk_tb`).
457
458 If *limit* is supplied, only this many frames are taken from *frame_gen*.
459 If *lookup_lines* is ``False``, the returned :class:`FrameSummary`
460 objects will not have read their lines in yet, making the cost of
461 creating the :class:`!StackSummary` cheaper (which may be valuable if it
462 may not actually get formatted). If *capture_locals* is ``True`` the
463 local variables in each :class:`!FrameSummary` are captured as object
464 representations.
465
466 .. versionchanged:: 3.12
467 Exceptions raised from :func:`repr` on a local variable (when
468 *capture_locals* is ``True``) are no longer propagated to the caller.
469
470 .. classmethod:: from_list(a_list)
471
472 Construct a :class:`!StackSummary` object from a supplied list of
473 :class:`FrameSummary` objects or old-style list of tuples. Each tuple
474 should be a 4-tuple with *filename*, *lineno*, *name*, *line* as the
475 elements.
476
477 .. method:: format()
478
479 Returns a list of strings ready for printing. Each string in the
480 resulting list corresponds to a single :ref:`frame <frame-objects>` from
481 the stack.
482 Each string ends in a newline; the strings may contain internal
483 newlines as well, for those items with source text lines.
484
485 For long sequences of the same frame and line, the first few
486 repetitions are shown, followed by a summary line stating the exact
487 number of further repetitions.
488
489 .. versionchanged:: 3.6
490 Long sequences of repeated frames are now abbreviated.
491
492 .. method:: format_frame_summary(frame_summary)
493
494 Returns a string for printing one of the :ref:`frames <frame-objects>`
495 involved in the stack.
496 This method is called for each :class:`FrameSummary` object to be
497 printed by :meth:`StackSummary.format`. If it returns ``None``, the
498 frame is omitted from the output.
499
500 .. versionadded:: 3.11
501
502
503 :class:`!FrameSummary` Objects
504 ------------------------------
505
506 .. versionadded:: 3.5
507
508 A :class:`!FrameSummary` object represents a single :ref:`frame <frame-objects>`
509 in a :ref:`traceback <traceback-objects>`.
510
511 .. class:: FrameSummary(filename, lineno, name, *,\
512 lookup_line=True, locals=None,\
513 line=None, end_lineno=None, colno=None, end_colno=None)
514
515 Represents a single :ref:`frame <frame-objects>` in the
516 :ref:`traceback <traceback-objects>` or stack that is being formatted
517 or printed. It may optionally have a stringified version of the frame's
518 locals included in it. If *lookup_line* is ``False``, the source code is not
519 looked up until the :class:`!FrameSummary` has the :attr:`~FrameSummary.line`
520 attribute accessed (which also happens when casting it to a :class:`tuple`).
521 :attr:`~FrameSummary.line` may be directly provided, and will prevent line
522 lookups happening at all. *locals* is an optional local variable
523 mapping, and if supplied the variable representations are stored in the
524 summary for later display.
525
526 :class:`!FrameSummary` instances have the following attributes:
527
528 .. attribute:: FrameSummary.filename
529
530 The filename of the source code for this frame. Equivalent to accessing
531 :attr:`f.f_code.co_filename <codeobject.co_filename>` on a
532 :ref:`frame object <frame-objects>` *f*.
533
534 .. attribute:: FrameSummary.lineno
535
536 The line number of the source code for this frame.
537
538 .. attribute:: FrameSummary.name
539
540 Equivalent to accessing :attr:`f.f_code.co_name <codeobject.co_name>` on
541 a :ref:`frame object <frame-objects>` *f*.
542
543 .. attribute:: FrameSummary.line
544
545 A string representing the source code for this frame, with leading and
546 trailing whitespace stripped.
547 If the source is not available, it is ``None``.
548
549 .. attribute:: FrameSummary.end_lineno
550
551 The last line number of the source code for this frame.
552 By default, it is set to ``lineno`` and indexation starts from 1.
553
554 .. versionchanged:: 3.13
555 The default value changed from ``None`` to ``lineno``.
556
557 .. attribute:: FrameSummary.colno
558
559 The column number of the source code for this frame.
560 By default, it is ``None`` and indexation starts from 0.
561
562 .. attribute:: FrameSummary.end_colno
563
564 The last column number of the source code for this frame.
565 By default, it is ``None`` and indexation starts from 0.
566
567
568 .. _traceback-example:
569
570 Examples of Using the Module-Level Functions
571 --------------------------------------------
572
573 This simple example implements a basic read-eval-print loop, similar to (but
574 less useful than) the standard Python interactive interpreter loop. For a more
575 complete implementation of the interpreter loop, refer to the :mod:`code`
576 module. ::
577
578 import sys, traceback
579
580 def run_user_code(envdir):
581 source = input(">>> ")
582 try:
583 exec(source, envdir)
584 except Exception:
585 print("Exception in user code:")
586 print("-"*60)
587 traceback.print_exc(file=sys.stdout)
588 print("-"*60)
589
590 envdir = {}
591 while True:
592 run_user_code(envdir)
593
594
595 The following example demonstrates the different ways to print and format the
596 exception and traceback:
597
598 .. testcode::
599
600 import sys, traceback
601
602 def lumberjack():
603 bright_side_of_life()
604
605 def bright_side_of_life():
606 return tuple()[0]
607
608 try:
609 lumberjack()
610 except IndexError as exc:
611 print("*** print_tb:")
612 traceback.print_tb(exc.__traceback__, limit=1, file=sys.stdout)
613 print("*** print_exception:")
614 traceback.print_exception(exc, limit=2, file=sys.stdout)
615 print("*** print_exc:")
616 traceback.print_exc(limit=2, file=sys.stdout)
617 print("*** format_exc, first and last line:")
618 formatted_lines = traceback.format_exc().splitlines()
619 print(formatted_lines[0])
620 print(formatted_lines[-1])
621 print("*** format_exception:")
622 print(repr(traceback.format_exception(exc)))
623 print("*** extract_tb:")
624 print(repr(traceback.extract_tb(exc.__traceback__)))
625 print("*** format_tb:")
626 print(repr(traceback.format_tb(exc.__traceback__)))
627 print("*** tb_lineno:", exc.__traceback__.tb_lineno)
628
629 The output for the example would look similar to this:
630
631 .. testoutput::
632 :options: +NORMALIZE_WHITESPACE
633
634 *** print_tb:
635 File "<doctest...>", line 10, in <module>
636 lumberjack()
637 ~~~~~~~~~~^^
638 *** print_exception:
639 Traceback (most recent call last):
640 File "<doctest...>", line 10, in <module>
641 lumberjack()
642 ~~~~~~~~~~^^
643 File "<doctest...>", line 4, in lumberjack
644 bright_side_of_life()
645 ~~~~~~~~~~~~~~~~~~~^^
646 IndexError: tuple index out of range
647 *** print_exc:
648 Traceback (most recent call last):
649 File "<doctest...>", line 10, in <module>
650 lumberjack()
651 ~~~~~~~~~~^^
652 File "<doctest...>", line 4, in lumberjack
653 bright_side_of_life()
654 ~~~~~~~~~~~~~~~~~~~^^
655 IndexError: tuple index out of range
656 *** format_exc, first and last line:
657 Traceback (most recent call last):
658 IndexError: tuple index out of range
659 *** format_exception:
660 ['Traceback (most recent call last):\n',
661 ' File "<doctest default[0]>", line 10, in <module>\n lumberjack()\n ~~~~~~~~~~^^\n',
662 ' File "<doctest default[0]>", line 4, in lumberjack\n bright_side_of_life()\n ~~~~~~~~~~~~~~~~~~~^^\n',
663 ' File "<doctest default[0]>", line 7, in bright_side_of_life\n return tuple()[0]\n ~~~~~~~^^^\n',
664 'IndexError: tuple index out of range\n']
665 *** extract_tb:
666 [<FrameSummary file <doctest...>, line 10 in <module>>,
667 <FrameSummary file <doctest...>, line 4 in lumberjack>,
668 <FrameSummary file <doctest...>, line 7 in bright_side_of_life>]
669 *** format_tb:
670 [' File "<doctest default[0]>", line 10, in <module>\n lumberjack()\n ~~~~~~~~~~^^\n',
671 ' File "<doctest default[0]>", line 4, in lumberjack\n bright_side_of_life()\n ~~~~~~~~~~~~~~~~~~~^^\n',
672 ' File "<doctest default[0]>", line 7, in bright_side_of_life\n return tuple()[0]\n ~~~~~~~^^^\n']
673 *** tb_lineno: 10
674
675
676 The following example shows the different ways to print and format the stack::
677
678 >>> import traceback
679 >>> def another_function():
680 ... lumberstack()
681 ...
682 >>> def lumberstack():
683 ... traceback.print_stack()
684 ... print(repr(traceback.extract_stack()))
685 ... print(repr(traceback.format_stack()))
686 ...
687 >>> another_function()
688 File "<doctest>", line 10, in <module>
689 another_function()
690 File "<doctest>", line 3, in another_function
691 lumberstack()
692 File "<doctest>", line 6, in lumberstack
693 traceback.print_stack()
694 [('<doctest>', 10, '<module>', 'another_function()'),
695 ('<doctest>', 3, 'another_function', 'lumberstack()'),
696 ('<doctest>', 7, 'lumberstack', 'print(repr(traceback.extract_stack()))')]
697 [' File "<doctest>", line 10, in <module>\n another_function()\n',
698 ' File "<doctest>", line 3, in another_function\n lumberstack()\n',
699 ' File "<doctest>", line 8, in lumberstack\n print(repr(traceback.format_stack()))\n']
700
701
702 This last example demonstrates the final few formatting functions:
703
704 .. doctest::
705 :options: +NORMALIZE_WHITESPACE
706
707 >>> import traceback
708 >>> traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'),
709 ... ('eggs.py', 42, 'eggs', 'return "bacon"')])
710 [' File "spam.py", line 3, in <module>\n spam.eggs()\n',
711 ' File "eggs.py", line 42, in eggs\n return "bacon"\n']
712 >>> an_error = IndexError('tuple index out of range')
713 >>> traceback.format_exception_only(an_error)
714 ['IndexError: tuple index out of range\n']
715
716
717 Examples of Using :class:`TracebackException`
718 ---------------------------------------------
719
720 With the helper class, we have more options::
721
722 >>> import sys
723 >>> from traceback import TracebackException
724 >>>
725 >>> def lumberjack():
726 ... bright_side_of_life()
727 ...
728 >>> def bright_side_of_life():
729 ... t = "bright", "side", "of", "life"
730 ... return t[5]
731 ...
732 >>> try:
733 ... lumberjack()
734 ... except IndexError as e:
735 ... exc = e
736 ...
737 >>> try:
738 ... try:
739 ... lumberjack()
740 ... except:
741 ... 1/0
742 ... except Exception as e:
743 ... chained_exc = e
744 ...
745 >>> # limit works as with the module-level functions
746 >>> TracebackException.from_exception(exc, limit=-2).print()
747 Traceback (most recent call last):
748 File "<python-input-1>", line 6, in lumberjack
749 bright_side_of_life()
750 ~~~~~~~~~~~~~~~~~~~^^
751 File "<python-input-1>", line 10, in bright_side_of_life
752 return t[5]
753 ~^^^
754 IndexError: tuple index out of range
755
756 >>> # capture_locals adds local variables in frames
757 >>> TracebackException.from_exception(exc, limit=-2, capture_locals=True).print()
758 Traceback (most recent call last):
759 File "<python-input-1>", line 6, in lumberjack
760 bright_side_of_life()
761 ~~~~~~~~~~~~~~~~~~~^^
762 File "<python-input-1>", line 10, in bright_side_of_life
763 return t[5]
764 ~^^^
765 t = ("bright", "side", "of", "life")
766 IndexError: tuple index out of range
767
768 >>> # The *chain* kwarg to print() controls whether chained
769 >>> # exceptions are displayed
770 >>> TracebackException.from_exception(chained_exc).print()
771 Traceback (most recent call last):
772 File "<python-input-19>", line 4, in <module>
773 lumberjack()
774 ~~~~~~~~~~^^
775 File "<python-input-8>", line 7, in lumberjack
776 bright_side_of_life()
777 ~~~~~~~~~~~~~~~~~~~^^
778 File "<python-input-8>", line 11, in bright_side_of_life
779 return t[5]
780 ~^^^
781 IndexError: tuple index out of range
782
783 During handling of the above exception, another exception occurred:
784
785 Traceback (most recent call last):
786 File "<python-input-19>", line 6, in <module>
787 1/0
788 ~^~
789 ZeroDivisionError: division by zero
790
791 >>> TracebackException.from_exception(chained_exc).print(chain=False)
792 Traceback (most recent call last):
793 File "<python-input-19>", line 6, in <module>
794 1/0
795 ~^~
796 ZeroDivisionError: division by zero
797