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