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