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