blob: dd3ae6947e907f0c6408eac7b1dd7e0a45366480 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`traceback` --- Print or retrieve a stack traceback
2========================================================
3
4.. module:: traceback
5 :synopsis: Print or retrieve a stack traceback.
6
7
8This module provides a standard interface to extract, format and print stack
9traces of Python programs. It exactly mimics the behavior of the Python
10interpreter when it prints a stack trace. This is useful when you want to print
11stack traces under program control, such as in a "wrapper" around the
12interpreter.
13
14.. index:: object: traceback
15
16The module uses traceback objects --- this is the object type that is stored in
17the ``sys.last_traceback`` variable and returned as the third item from
18:func:`sys.exc_info`.
19
20The module defines the following functions:
21
22
23.. function:: print_tb(traceback[, limit[, file]])
24
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.
29
30
Georg Brandl1aea30a2008-07-19 15:51:07 +000031.. function:: print_exception(type, value, traceback[, limit[, file[, chain]]])
Georg Brandl116aa622007-08-15 14:28:22 +000032
33 Print exception information and up to *limit* stack trace entries from
Georg Brandl1aea30a2008-07-19 15:51:07 +000034 *traceback* to *file*. This differs from :func:`print_tb` in the following
35 ways:
36
37 * if *traceback* is not ``None``, it prints a header ``Traceback (most recent
38 call last):``
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.
43
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
47 exception.
Georg Brandl116aa622007-08-15 14:28:22 +000048
49
Georg Brandl1aea30a2008-07-19 15:51:07 +000050.. function:: print_exc([limit[, file[, chain]]])
Georg Brandl116aa622007-08-15 14:28:22 +000051
Georg Brandlf6945182008-02-01 11:56:49 +000052 This is a shorthand for ``print_exception(*sys.exc_info())``.
Georg Brandl116aa622007-08-15 14:28:22 +000053
54
Georg Brandl1aea30a2008-07-19 15:51:07 +000055.. function:: print_last([limit[, file[, chain]]])
Georg Brandl116aa622007-08-15 14:28:22 +000056
57 This is a shorthand for ``print_exception(sys.last_type, sys.last_value,
58 sys.last_traceback, limit, file)``.
59
60
61.. function:: print_stack([f[, limit[, file]]])
62
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`.
67
68
69.. function:: extract_tb(traceback[, limit])
70
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``.
78
79
80.. function:: extract_stack([f[, limit]])
81
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`.
85
86
87.. function:: format_list(list)
88
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``.
94
95
96.. function:: format_exception_only(type, value)
97
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.
105
106
Georg Brandl1aea30a2008-07-19 15:51:07 +0000107.. function:: format_exception(type, value, tb[, limit[, chain]])
Georg Brandl116aa622007-08-15 14:28:22 +0000108
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`.
114
115
Georg Brandl1aea30a2008-07-19 15:51:07 +0000116.. function:: format_exc([limit[, chain]])
117
118 This is like ``print_exc(limit)`` but returns a string instead of printing to a
119 file.
120
121
Georg Brandl116aa622007-08-15 14:28:22 +0000122.. function:: format_tb(tb[, limit])
123
124 A shorthand for ``format_list(extract_tb(tb, limit))``.
125
126
127.. function:: format_stack([f[, limit]])
128
129 A shorthand for ``format_list(extract_stack(f, limit))``.
130
131
Georg Brandl116aa622007-08-15 14:28:22 +0000132.. _traceback-example:
133
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000134Traceback Examples
135------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000136
137This simple example implements a basic read-eval-print loop, similar to (but
138less useful than) the standard Python interactive interpreter loop. For a more
139complete implementation of the interpreter loop, refer to the :mod:`code`
140module. ::
141
142 import sys, traceback
143
144 def run_user_code(envdir):
Georg Brandl8d5c3922007-12-02 22:48:17 +0000145 source = input(">>> ")
Georg Brandl116aa622007-08-15 14:28:22 +0000146 try:
147 exec(source, envdir)
148 except:
Collin Winterc79461b2007-09-01 23:34:30 +0000149 print("Exception in user code:")
150 print("-"*60)
Georg Brandl116aa622007-08-15 14:28:22 +0000151 traceback.print_exc(file=sys.stdout)
Collin Winterc79461b2007-09-01 23:34:30 +0000152 print("-"*60)
Georg Brandl116aa622007-08-15 14:28:22 +0000153
154 envdir = {}
Collin Winterc79461b2007-09-01 23:34:30 +0000155 while True:
Georg Brandl116aa622007-08-15 14:28:22 +0000156 run_user_code(envdir)
157
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000158
159The following example demonstrates the different ways to print and format the
160exception and traceback::
161
162 import sys, traceback
163
164 def lumberjack():
165 bright_side_of_death()
166
167 def bright_side_of_death():
168 return tuple()[0]
169
170 try:
171 lumberjack()
172 except:
173 exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
Georg Brandlf6945182008-02-01 11:56:49 +0000174 print("*** print_tb:")
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000175 traceback.print_tb(exceptionTraceback, limit=1, file=sys.stdout)
Georg Brandlf6945182008-02-01 11:56:49 +0000176 print("*** print_exception:")
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000177 traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
178 limit=2, file=sys.stdout)
Georg Brandlf6945182008-02-01 11:56:49 +0000179 print("*** print_exc:")
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000180 traceback.print_exc()
Georg Brandlf6945182008-02-01 11:56:49 +0000181 print("*** format_exc, first and last line:")
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000182 formatted_lines = traceback.format_exc().splitlines()
Georg Brandlf6945182008-02-01 11:56:49 +0000183 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:")
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000194 traceback.print_last()
195
196
197The output for the example would look similar to this::
198
199 *** print_tb:
200 File "<doctest>", line 9, in <module>
201 lumberjack()
202 *** print_exception:
203 Traceback (most recent call last):
204 File "<doctest>", line 9, in <module>
205 lumberjack()
206 File "<doctest>", line 3, in lumberjack
207 bright_side_of_death()
208 IndexError: tuple index out of range
209 *** print_exc:
210 Traceback (most recent call last):
211 File "<doctest>", line 9, in <module>
212 lumberjack()
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']
225 *** extract_tb:
226 [('<doctest>', 9, '<module>', 'lumberjack()'),
227 ('<doctest>', 3, 'lumberjack', 'bright_side_of_death()'),
228 ('<doctest>', 6, 'bright_side_of_death', 'return tuple()[0]')]
229 *** format_tb:
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']
233 *** tb_lineno: 2
234 *** print_last:
235 Traceback (most recent call last):
236 File "<doctest>", line 9, in <module>
237 lumberjack()
238 File "<doctest>", line 3, in lumberjack
239 bright_side_of_death()
240 IndexError: tuple index out of range
241
242
243The following example shows the different ways to print and format the stack::
244
245 >>> import traceback
246 >>> def another_function():
247 ... lumberstack()
248 ...
249 >>> def lumberstack():
250 ... traceback.print_stack()
Georg Brandlf6945182008-02-01 11:56:49 +0000251 ... print(repr(traceback.extract_stack()))
252 ... print(repr(traceback.format_stack()))
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000253 ...
254 >>> another_function()
255 File "<doctest>", line 10, in <module>
256 another_function()
257 File "<doctest>", line 3, in another_function
258 lumberstack()
259 File "<doctest>", line 6, in lumberstack
260 traceback.print_stack()
261 [('<doctest>', 10, '<module>', 'another_function()'),
262 ('<doctest>', 3, 'another_function', 'lumberstack()'),
Georg Brandlf6945182008-02-01 11:56:49 +0000263 ('<doctest>', 7, 'lumberstack', 'print(repr(traceback.extract_stack()))')]
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000264 [' File "<doctest>", line 10, in <module>\n another_function()\n',
265 ' File "<doctest>", line 3, in another_function\n lumberstack()\n',
Georg Brandlf6945182008-02-01 11:56:49 +0000266 ' File "<doctest>", line 8, in lumberstack\n print(repr(traceback.format_stack()))\n']
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000267
268
269This last example demonstrates the final few formatting functions::
270
271 >>> import traceback
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']