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
11This module provides a standard interface to extract, format and print stack
12traces of Python programs.  It exactly mimics the behavior of the Python
13interpreter when it prints a stack trace.  This is useful when you want to print
14stack traces under program control, such as in a "wrapper" around the
15interpreter.
16
17.. index:: pair: object; traceback
18
19The module uses traceback objects --- these are objects of type :class:`types.TracebackType`,
20which are assigned to the ``__traceback__`` field of :class:`BaseException` instances.
21
22.. seealso::
23
24   Module :mod:`faulthandler`
25      Used to dump Python tracebacks explicitly, on a fault, after a timeout, or on a user signal.
26
27   Module :mod:`pdb`
28      Interactive source code debugger for Python programs.
29
30The module defines the following functions:
31
32.. function:: print_tb(tb, limit=None, file=None)
33
34   Print up to *limit* stack trace entries from traceback object *tb* (starting
35   from the caller's frame) if *limit* is positive.  Otherwise, print the last
36   ``abs(limit)`` entries.  If *limit* is omitted or ``None``, all entries are
37   printed.  If *file* is omitted or ``None``, the output goes to
38   ``sys.stderr``; otherwise it should be an open file or file-like object to
39   receive the output.
40
41   .. versionchanged:: 3.5
42       Added negative *limit* support.
43
44
45.. function:: print_exception(exc, /[, value, tb], limit=None, \
46                              file=None, chain=True)
47
48   Print exception information and stack trace entries from traceback object
49   *tb* to *file*. This differs from :func:`print_tb` in the following
50   ways:
51
52   * if *tb* is not ``None``, it prints a header ``Traceback (most recent
53     call last):``
54
55   * it prints the exception type and *value* after the stack trace
56
57   .. index:: single: ^ (caret); marker
58
59   * if *type(value)* is :exc:`SyntaxError` and *value* has the appropriate
60     format, it prints the line where the syntax error occurred with a caret
61     indicating the approximate position of the error.
62
63   Since Python 3.10, instead of passing *value* and *tb*, an exception object
64   can be passed as the first argument. If *value* and *tb* are provided, the
65   first argument is ignored in order to provide backwards compatibility.
66
67   The optional *limit* argument has the same meaning as for :func:`print_tb`.
68   If *chain* is true (the default), then chained exceptions (the
69   :attr:`__cause__` or :attr:`__context__` attributes of the exception) will be
70   printed as well, like the interpreter itself does when printing an unhandled
71   exception.
72
73   .. versionchanged:: 3.5
74      The *etype* argument is ignored and inferred from the type of *value*.
75
76   .. versionchanged:: 3.10
77      The *etype* parameter has been renamed to *exc* and is now
78      positional-only.
79
80
81.. function:: print_exc(limit=None, file=None, chain=True)
82
83   This is a shorthand for ``print_exception(sys.exception(), limit, file,
84   chain)``.
85
86
87.. function:: print_last(limit=None, file=None, chain=True)
88
89   This is a shorthand for ``print_exception(sys.last_type, sys.last_value,
90   sys.last_traceback, limit, file, chain)``.  In general it will work only
91   after an exception has reached an interactive prompt (see
92   :data:`sys.last_type`).
93
94
95.. function:: print_stack(f=None, limit=None, file=None)
96
97   Print up to *limit* stack trace entries (starting from the invocation
98   point) if *limit* is positive.  Otherwise, print the last ``abs(limit)``
99   entries.  If *limit* is omitted or ``None``, all entries are printed.
100   The optional *f* argument can be used to specify an alternate stack frame
101   to start.  The optional *file* argument has the same meaning as for
102   :func:`print_tb`.
103
104   .. versionchanged:: 3.5
105          Added negative *limit* support.
106
107
108.. function:: extract_tb(tb, limit=None)
109
110   Return a :class:`StackSummary` object representing a list of "pre-processed"
111   stack trace entries extracted from the traceback object *tb*.  It is useful
112   for alternate formatting of stack traces.  The optional *limit* argument has
113   the same meaning as for :func:`print_tb`.  A "pre-processed" stack trace
114   entry is a :class:`FrameSummary` object containing attributes
115   :attr:`~FrameSummary.filename`, :attr:`~FrameSummary.lineno`,
116   :attr:`~FrameSummary.name`, and :attr:`~FrameSummary.line` representing the
117   information that is usually printed for a stack trace.  The
118   :attr:`~FrameSummary.line` is a string with leading and trailing
119   whitespace stripped; if the source is not available it is ``None``.
120
121
122.. function:: extract_stack(f=None, limit=None)
123
124   Extract the raw traceback from the current stack frame.  The return value has
125   the same format as for :func:`extract_tb`.  The optional *f* and *limit*
126   arguments have the same meaning as for :func:`print_stack`.
127
128
129.. function:: format_list(extracted_list)
130
131   Given a list of tuples or :class:`FrameSummary` objects as returned by
132   :func:`extract_tb` or :func:`extract_stack`, return a list of strings ready
133   for printing.  Each string in the resulting list corresponds to the item with
134   the same index in the argument list.  Each string ends in a newline; the
135   strings may contain internal newlines as well, for those items whose source
136   text line is not ``None``.
137
138
139.. function:: format_exception_only(exc, /[, value])
140
141   Format the exception part of a traceback using an exception value such as
142   given by ``sys.last_value``.  The return value is a list of strings, each
143   ending in a newline.  Normally, the list contains a single string; however,
144   for :exc:`SyntaxError` exceptions, it contains several lines that (when
145   printed) display detailed information about where the syntax error occurred.
146   The message indicating which exception occurred is the always last string in
147   the list.
148
149   Since Python 3.10, instead of passing *value*, an exception object
150   can be passed as the first argument.  If *value* is provided, the first
151   argument is ignored in order to provide backwards compatibility.
152
153   .. versionchanged:: 3.10
154      The *etype* parameter has been renamed to *exc* and is now
155      positional-only.
156
157
158.. function:: format_exception(exc, /[, value, tb], limit=None, chain=True)
159
160   Format a stack trace and the exception information.  The arguments  have the
161   same meaning as the corresponding arguments to :func:`print_exception`.  The
162   return value is a list of strings, each ending in a newline and some
163   containing internal newlines.  When these lines are concatenated and printed,
164   exactly the same text is printed as does :func:`print_exception`.
165
166   .. versionchanged:: 3.5
167      The *etype* argument is ignored and inferred from the type of *value*.
168
169   .. versionchanged:: 3.10
170      This function's behavior and signature were modified to match
171      :func:`print_exception`.
172
173
174.. function:: format_exc(limit=None, chain=True)
175
176   This is like ``print_exc(limit)`` but returns a string instead of printing to
177   a file.
178
179
180.. function:: format_tb(tb, limit=None)
181
182   A shorthand for ``format_list(extract_tb(tb, limit))``.
183
184
185.. function:: format_stack(f=None, limit=None)
186
187   A shorthand for ``format_list(extract_stack(f, limit))``.
188
189.. function:: clear_frames(tb)
190
191   Clears the local variables of all the stack frames in a traceback *tb*
192   by calling the :meth:`clear` method of each frame object.
193
194   .. versionadded:: 3.4
195
196.. function:: walk_stack(f)
197
198   Walk a stack following ``f.f_back`` from the given frame, yielding the frame
199   and line number for each frame. If *f* is ``None``, the current stack is
200   used. This helper is used with :meth:`StackSummary.extract`.
201
202   .. versionadded:: 3.5
203
204.. function:: walk_tb(tb)
205
206   Walk a traceback following ``tb_next`` yielding the frame and line number
207   for each frame. This helper is used with :meth:`StackSummary.extract`.
208
209   .. versionadded:: 3.5
210
211The module also defines the following classes:
212
213:class:`TracebackException` Objects
214-----------------------------------
215
216.. versionadded:: 3.5
217
218:class:`TracebackException` objects are created from actual exceptions to
219capture data for later printing in a lightweight fashion.
220
221.. 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)
222
223   Capture an exception for later rendering. *limit*, *lookup_lines* and
224   *capture_locals* are as for the :class:`StackSummary` class.
225
226   If *compact* is true, only data that is required by :class:`TracebackException`'s
227   ``format`` method is saved in the class attributes. In particular, the
228   ``__context__`` field is calculated only if ``__cause__`` is ``None`` and
229   ``__suppress_context__`` is false.
230
231   Note that when locals are captured, they are also shown in the traceback.
232
233   *max_group_width* and *max_group_depth* control the formatting of exception
234   groups (see :exc:`BaseExceptionGroup`). The depth refers to the nesting
235   level of the group, and the width refers to the size of a single exception
236   group's exceptions array. The formatted output is truncated when either
237   limit is exceeded.
238
239   .. attribute:: __cause__
240
241      A :class:`TracebackException` of the original ``__cause__``.
242
243   .. attribute:: __context__
244
245      A :class:`TracebackException` of the original ``__context__``.
246
247   .. attribute:: exceptions
248
249      If ``self`` represents an :exc:`ExceptionGroup`, this field holds a list of
250      :class:`TracebackException` instances representing the nested exceptions.
251      Otherwise it is ``None``.
252
253      .. versionadded:: 3.11
254
255   .. attribute:: __suppress_context__
256
257      The ``__suppress_context__`` value from the original exception.
258
259   .. attribute:: __notes__
260
261      The ``__notes__`` value from the original exception, or ``None``
262      if the exception does not have any notes. If it is not ``None``
263      is it formatted in the traceback after the exception string.
264
265      .. versionadded:: 3.11
266
267   .. attribute:: stack
268
269      A :class:`StackSummary` representing the traceback.
270
271   .. attribute:: exc_type
272
273      The class of the original traceback.
274
275   .. attribute:: filename
276
277      For syntax errors - the file name where the error occurred.
278
279   .. attribute:: lineno
280
281      For syntax errors - the line number where the error occurred.
282
283   .. attribute:: end_lineno
284
285      For syntax errors - the end line number where the error occurred.
286      Can be ``None`` if not present.
287
288      .. versionadded:: 3.10
289
290   .. attribute:: text
291
292      For syntax errors - the text where the error occurred.
293
294   .. attribute:: offset
295
296      For syntax errors - the offset into the text where the error occurred.
297
298   .. attribute:: end_offset
299
300      For syntax errors - the end offset into the text where the error occurred.
301      Can be ``None`` if not present.
302
303      .. versionadded:: 3.10
304
305   .. attribute:: msg
306
307      For syntax errors - the compiler error message.
308
309   .. classmethod:: from_exception(exc, *, limit=None, lookup_lines=True, capture_locals=False)
310
311      Capture an exception for later rendering. *limit*, *lookup_lines* and
312      *capture_locals* are as for the :class:`StackSummary` class.
313
314      Note that when locals are captured, they are also shown in the traceback.
315
316   .. method::  print(*, file=None, chain=True)
317
318      Print to *file* (default ``sys.stderr``) the exception information returned by
319      :meth:`format`.
320
321      .. versionadded:: 3.11
322
323   .. method:: format(*, chain=True)
324
325      Format the exception.
326
327      If *chain* is not ``True``, ``__cause__`` and ``__context__`` will not
328      be formatted.
329
330      The return value is a generator of strings, each ending in a newline and
331      some containing internal newlines. :func:`~traceback.print_exception`
332      is a wrapper around this method which just prints the lines to a file.
333
334      The message indicating which exception occurred is always the last
335      string in the output.
336
337   .. method::  format_exception_only()
338
339      Format the exception part of the traceback.
340
341      The return value is a generator of strings, each ending in a newline.
342
343      Normally, the generator emits a single string; however, for
344      :exc:`SyntaxError` exceptions, it emits several lines that (when
345      printed) display detailed information about where the syntax
346      error occurred.
347
348      The message indicating which exception occurred is always the last
349      string in the output.
350
351   .. versionchanged:: 3.10
352      Added the *compact* parameter.
353
354   .. versionchanged:: 3.11
355      Added the *max_group_width* and *max_group_depth* parameters.
356
357
358:class:`StackSummary` Objects
359-----------------------------
360
361.. versionadded:: 3.5
362
363:class:`StackSummary` objects represent a call stack ready for formatting.
364
365.. class:: StackSummary
366
367   .. classmethod:: extract(frame_gen, *, limit=None, lookup_lines=True, capture_locals=False)
368
369      Construct a :class:`StackSummary` object from a frame generator (such as
370      is returned by :func:`~traceback.walk_stack` or
371      :func:`~traceback.walk_tb`).
372
373      If *limit* is supplied, only this many frames are taken from *frame_gen*.
374      If *lookup_lines* is ``False``, the returned :class:`FrameSummary`
375      objects will not have read their lines in yet, making the cost of
376      creating the :class:`StackSummary` cheaper (which may be valuable if it
377      may not actually get formatted). If *capture_locals* is ``True`` the
378      local variables in each :class:`FrameSummary` are captured as object
379      representations.
380
381   .. classmethod:: from_list(a_list)
382
383      Construct a :class:`StackSummary` object from a supplied list of
384      :class:`FrameSummary` objects or old-style list of tuples.  Each tuple
385      should be a 4-tuple with filename, lineno, name, line as the elements.
386
387   .. method:: format()
388
389      Returns a list of strings ready for printing.  Each string in the
390      resulting list corresponds to a single frame from the stack.
391      Each string ends in a newline; the strings may contain internal
392      newlines as well, for those items with source text lines.
393
394      For long sequences of the same frame and line, the first few
395      repetitions are shown, followed by a summary line stating the exact
396      number of further repetitions.
397
398      .. versionchanged:: 3.6
399         Long sequences of repeated frames are now abbreviated.
400
401   .. method:: format_frame_summary(frame_summary)
402
403      Returns a string for printing one of the frames involved in the stack.
404      This method is called for each :class:`FrameSummary` object to be
405      printed by :meth:`StackSummary.format`. If it returns ``None``, the
406      frame is omitted from the output.
407
408      .. versionadded:: 3.11
409
410
411:class:`FrameSummary` Objects
412-----------------------------
413
414.. versionadded:: 3.5
415
416A :class:`FrameSummary` object represents a single frame in a traceback.
417
418.. class:: FrameSummary(filename, lineno, name, lookup_line=True, locals=None, line=None)
419
420   Represent a single frame in the traceback or stack that is being formatted
421   or printed. It may optionally have a stringified version of the frames
422   locals included in it. If *lookup_line* is ``False``, the source code is not
423   looked up until the :class:`FrameSummary` has the :attr:`~FrameSummary.line`
424   attribute accessed (which also happens when casting it to a tuple).
425   :attr:`~FrameSummary.line` may be directly provided, and will prevent line
426   lookups happening at all. *locals* is an optional local variable
427   dictionary, and if supplied the variable representations are stored in the
428   summary for later display.
429
430.. _traceback-example:
431
432Traceback Examples
433------------------
434
435This simple example implements a basic read-eval-print loop, similar to (but
436less useful than) the standard Python interactive interpreter loop.  For a more
437complete implementation of the interpreter loop, refer to the :mod:`code`
438module. ::
439
440   import sys, traceback
441
442   def run_user_code(envdir):
443       source = input(">>> ")
444       try:
445           exec(source, envdir)
446       except Exception:
447           print("Exception in user code:")
448           print("-"*60)
449           traceback.print_exc(file=sys.stdout)
450           print("-"*60)
451
452   envdir = {}
453   while True:
454       run_user_code(envdir)
455
456
457The following example demonstrates the different ways to print and format the
458exception and traceback:
459
460.. testcode::
461
462   import sys, traceback
463
464   def lumberjack():
465       bright_side_of_life()
466
467   def bright_side_of_life():
468       return tuple()[0]
469
470   try:
471       lumberjack()
472   except IndexError:
473       exc = sys.exception()
474       print("*** print_tb:")
475       traceback.print_tb(exc.__traceback__, limit=1, file=sys.stdout)
476       print("*** print_exception:")
477       traceback.print_exception(exc, limit=2, file=sys.stdout)
478       print("*** print_exc:")
479       traceback.print_exc(limit=2, file=sys.stdout)
480       print("*** format_exc, first and last line:")
481       formatted_lines = traceback.format_exc().splitlines()
482       print(formatted_lines[0])
483       print(formatted_lines[-1])
484       print("*** format_exception:")
485       print(repr(traceback.format_exception(exc)))
486       print("*** extract_tb:")
487       print(repr(traceback.extract_tb(exc.__traceback__)))
488       print("*** format_tb:")
489       print(repr(traceback.format_tb(exc.__traceback__)))
490       print("*** tb_lineno:", exc.__traceback__.tb_lineno)
491
492The output for the example would look similar to this:
493
494.. testoutput::
495   :options: +NORMALIZE_WHITESPACE
496
497   *** print_tb:
498     File "<doctest...>", line 10, in <module>
499       lumberjack()
500   *** print_exception:
501   Traceback (most recent call last):
502     File "<doctest...>", line 10, in <module>
503       lumberjack()
504     File "<doctest...>", line 4, in lumberjack
505       bright_side_of_life()
506   IndexError: tuple index out of range
507   *** print_exc:
508   Traceback (most recent call last):
509     File "<doctest...>", line 10, in <module>
510       lumberjack()
511     File "<doctest...>", line 4, in lumberjack
512       bright_side_of_life()
513   IndexError: tuple index out of range
514   *** format_exc, first and last line:
515   Traceback (most recent call last):
516   IndexError: tuple index out of range
517   *** format_exception:
518   ['Traceback (most recent call last):\n',
519    '  File "<doctest default[0]>", line 10, in <module>\n    lumberjack()\n',
520    '  File "<doctest default[0]>", line 4, in lumberjack\n    bright_side_of_life()\n',
521    '  File "<doctest default[0]>", line 7, in bright_side_of_life\n    return tuple()[0]\n           ~~~~~~~^^^\n',
522    'IndexError: tuple index out of range\n']
523   *** extract_tb:
524   [<FrameSummary file <doctest...>, line 10 in <module>>,
525    <FrameSummary file <doctest...>, line 4 in lumberjack>,
526    <FrameSummary file <doctest...>, line 7 in bright_side_of_life>]
527   *** format_tb:
528   ['  File "<doctest default[0]>", line 10, in <module>\n    lumberjack()\n',
529    '  File "<doctest default[0]>", line 4, in lumberjack\n    bright_side_of_life()\n',
530    '  File "<doctest default[0]>", line 7, in bright_side_of_life\n    return tuple()[0]\n           ~~~~~~~^^^\n']
531   *** tb_lineno: 10
532
533
534The following example shows the different ways to print and format the stack::
535
536   >>> import traceback
537   >>> def another_function():
538   ...     lumberstack()
539   ...
540   >>> def lumberstack():
541   ...     traceback.print_stack()
542   ...     print(repr(traceback.extract_stack()))
543   ...     print(repr(traceback.format_stack()))
544   ...
545   >>> another_function()
546     File "<doctest>", line 10, in <module>
547       another_function()
548     File "<doctest>", line 3, in another_function
549       lumberstack()
550     File "<doctest>", line 6, in lumberstack
551       traceback.print_stack()
552   [('<doctest>', 10, '<module>', 'another_function()'),
553    ('<doctest>', 3, 'another_function', 'lumberstack()'),
554    ('<doctest>', 7, 'lumberstack', 'print(repr(traceback.extract_stack()))')]
555   ['  File "<doctest>", line 10, in <module>\n    another_function()\n',
556    '  File "<doctest>", line 3, in another_function\n    lumberstack()\n',
557    '  File "<doctest>", line 8, in lumberstack\n    print(repr(traceback.format_stack()))\n']
558
559
560This last example demonstrates the final few formatting functions:
561
562.. doctest::
563   :options: +NORMALIZE_WHITESPACE
564
565   >>> import traceback
566   >>> traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'),
567   ...                        ('eggs.py', 42, 'eggs', 'return "bacon"')])
568   ['  File "spam.py", line 3, in <module>\n    spam.eggs()\n',
569    '  File "eggs.py", line 42, in eggs\n    return "bacon"\n']
570   >>> an_error = IndexError('tuple index out of range')
571   >>> traceback.format_exception_only(type(an_error), an_error)
572   ['IndexError: tuple index out of range\n']
573