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