1
:mod:`traceback` --- Print or retrieve a stack traceback
2
========================================================
5
:synopsis: Print or retrieve a stack traceback.
8
This module provides a standard interface to extract, format and print stack
9
traces of Python programs. It exactly mimics the behavior of the Python
10
interpreter when it prints a stack trace. This is useful when you want to print
11
stack traces under program control, such as in a "wrapper" around the
14
.. index:: object: traceback
16
The module uses traceback objects --- this is the object type that is stored in
17
the ``sys.last_traceback`` variable and returned as the third item from
20
The module defines the following functions:
23
.. function:: print_tb(traceback[, limit[, file]])
25
Print up to *limit* stack trace entries from *traceback*. If *limit* is omitted
26
or ``None``, all entries are printed. If *file* is omitted or ``None``, the
27
output goes to ``sys.stderr``; otherwise it should be an open file or file-like
28
object to receive the output.
31
.. function:: print_exception(type, value, traceback[, limit[, file[, chain]]])
33
Print exception information and up to *limit* stack trace entries from
34
*traceback* to *file*. This differs from :func:`print_tb` in the following
37
* if *traceback* is not ``None``, it prints a header ``Traceback (most recent
39
* it prints the exception *type* and *value* after the stack trace
40
* if *type* is :exc:`SyntaxError` and *value* has the appropriate format, it
41
prints the line where the syntax error occurred with a caret indicating the
42
approximate position of the error.
44
If *chain* is true (the default), then chained exceptions (the
45
:attr:`__cause__` or :attr:`__context__` attributes of the exception) will be
46
printed as well, like the interpreter itself does when printing an unhandled
50
.. function:: print_exc([limit[, file[, chain]]])
52
This is a shorthand for ``print_exception(*sys.exc_info())``.
55
.. function:: print_last([limit[, file[, chain]]])
57
This is a shorthand for ``print_exception(sys.last_type, sys.last_value,
58
sys.last_traceback, limit, file)``.
61
.. function:: print_stack([f[, limit[, file]]])
63
This function prints a stack trace from its invocation point. The optional *f*
64
argument can be used to specify an alternate stack frame to start. The optional
65
*limit* and *file* arguments have the same meaning as for
66
:func:`print_exception`.
69
.. function:: extract_tb(traceback[, limit])
71
Return a list of up to *limit* "pre-processed" stack trace entries extracted
72
from the traceback object *traceback*. It is useful for alternate formatting of
73
stack traces. If *limit* is omitted or ``None``, all entries are extracted. A
74
"pre-processed" stack trace entry is a quadruple (*filename*, *line number*,
75
*function name*, *text*) representing the information that is usually printed
76
for a stack trace. The *text* is a string with leading and trailing whitespace
77
stripped; if the source is not available it is ``None``.
80
.. function:: extract_stack([f[, limit]])
82
Extract the raw traceback from the current stack frame. The return value has
83
the same format as for :func:`extract_tb`. The optional *f* and *limit*
84
arguments have the same meaning as for :func:`print_stack`.
87
.. function:: format_list(list)
89
Given a list of tuples as returned by :func:`extract_tb` or
90
:func:`extract_stack`, return a list of strings ready for printing. Each string
91
in the resulting list corresponds to the item with the same index in the
92
argument list. Each string ends in a newline; the strings may contain internal
93
newlines as well, for those items whose source text line is not ``None``.
96
.. function:: format_exception_only(type, value)
98
Format the exception part of a traceback. The arguments are the exception type
99
and value such as given by ``sys.last_type`` and ``sys.last_value``. The return
100
value is a list of strings, each ending in a newline. Normally, the list
101
contains a single string; however, for :exc:`SyntaxError` exceptions, it
102
contains several lines that (when printed) display detailed information about
103
where the syntax error occurred. The message indicating which exception
104
occurred is the always last string in the list.
107
.. function:: format_exception(type, value, tb[, limit[, chain]])
109
Format a stack trace and the exception information. The arguments have the
110
same meaning as the corresponding arguments to :func:`print_exception`. The
111
return value is a list of strings, each ending in a newline and some containing
112
internal newlines. When these lines are concatenated and printed, exactly the
113
same text is printed as does :func:`print_exception`.
116
.. function:: format_exc([limit[, chain]])
118
This is like ``print_exc(limit)`` but returns a string instead of printing to a
122
.. function:: format_tb(tb[, limit])
124
A shorthand for ``format_list(extract_tb(tb, limit))``.
127
.. function:: format_stack([f[, limit]])
129
A shorthand for ``format_list(extract_stack(f, limit))``.
132
.. _traceback-example:
137
This simple example implements a basic read-eval-print loop, similar to (but
138
less useful than) the standard Python interactive interpreter loop. For a more
139
complete implementation of the interpreter loop, refer to the :mod:`code`
142
import sys, traceback
144
def run_user_code(envdir):
145
source = input(">>> ")
149
print("Exception in user code:")
151
traceback.print_exc(file=sys.stdout)
156
run_user_code(envdir)
159
The following example demonstrates the different ways to print and format the
160
exception and traceback::
162
import sys, traceback
165
bright_side_of_death()
167
def bright_side_of_death():
173
exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
174
print("*** print_tb:")
175
traceback.print_tb(exceptionTraceback, limit=1, file=sys.stdout)
176
print("*** print_exception:")
177
traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
178
limit=2, file=sys.stdout)
179
print("*** print_exc:")
180
traceback.print_exc()
181
print("*** format_exc, first and last line:")
182
formatted_lines = traceback.format_exc().splitlines()
183
print(formatted_lines[0])
184
print(formatted_lines[-1])
185
print("*** format_exception:")
186
print(repr(traceback.format_exception(exceptionType, exceptionValue,
187
exceptionTraceback)))
188
print("*** extract_tb:")
189
print(repr(traceback.extract_tb(exceptionTraceback)))
190
print("*** format_tb:")
191
print(repr(traceback.format_tb(exceptionTraceback)))
192
print("*** tb_lineno:", traceback.tb_lineno(exceptionTraceback))
193
print("*** print_last:")
194
traceback.print_last()
197
The output for the example would look similar to this::
200
File "<doctest>", line 9, in <module>
203
Traceback (most recent call last):
204
File "<doctest>", line 9, in <module>
206
File "<doctest>", line 3, in lumberjack
207
bright_side_of_death()
208
IndexError: tuple index out of range
210
Traceback (most recent call last):
211
File "<doctest>", line 9, in <module>
213
File "<doctest>", line 3, in lumberjack
214
bright_side_of_death()
215
IndexError: tuple index out of range
216
*** format_exc, first and last line:
217
Traceback (most recent call last):
218
IndexError: tuple index out of range
219
*** format_exception:
220
['Traceback (most recent call last):\n',
221
' File "<doctest>", line 9, in <module>\n lumberjack()\n',
222
' File "<doctest>", line 3, in lumberjack\n bright_side_of_death()\n',
223
' File "<doctest>", line 6, in bright_side_of_death\n return tuple()[0]\n',
224
'IndexError: tuple index out of range\n']
226
[('<doctest>', 9, '<module>', 'lumberjack()'),
227
('<doctest>', 3, 'lumberjack', 'bright_side_of_death()'),
228
('<doctest>', 6, 'bright_side_of_death', 'return tuple()[0]')]
230
[' File "<doctest>", line 9, in <module>\n lumberjack()\n',
231
' File "<doctest>", line 3, in lumberjack\n bright_side_of_death()\n',
232
' File "<doctest>", line 6, in bright_side_of_death\n return tuple()[0]\n']
235
Traceback (most recent call last):
236
File "<doctest>", line 9, in <module>
238
File "<doctest>", line 3, in lumberjack
239
bright_side_of_death()
240
IndexError: tuple index out of range
243
The following example shows the different ways to print and format the stack::
246
>>> def another_function():
249
>>> def lumberstack():
250
... traceback.print_stack()
251
... print(repr(traceback.extract_stack()))
252
... print(repr(traceback.format_stack()))
254
>>> another_function()
255
File "<doctest>", line 10, in <module>
257
File "<doctest>", line 3, in another_function
259
File "<doctest>", line 6, in lumberstack
260
traceback.print_stack()
261
[('<doctest>', 10, '<module>', 'another_function()'),
262
('<doctest>', 3, 'another_function', 'lumberstack()'),
263
('<doctest>', 7, 'lumberstack', 'print(repr(traceback.extract_stack()))')]
264
[' File "<doctest>", line 10, in <module>\n another_function()\n',
265
' File "<doctest>", line 3, in another_function\n lumberstack()\n',
266
' File "<doctest>", line 8, in lumberstack\n print(repr(traceback.format_stack()))\n']
269
This last example demonstrates the final few formatting functions::
272
>>> format_list([('spam.py', 3, '<module>', 'spam.eggs()'),
273
... ('eggs.py', 42, 'eggs', 'return "bacon"')])
274
[' File "spam.py", line 3, in <module>\n spam.eggs()\n',
275
' File "eggs.py", line 42, in eggs\n return "bacon"\n']
276
>>> theError = IndexError('tuple indx out of range')
277
>>> traceback.format_exception_only(type(theError), theError)
278
['IndexError: tuple index out of range\n']