blob: 5e611416bffc42cd08b4cd1e2a644a7f76f7287e [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Senthil Kumaran11a73892016-01-15 22:13:16 -080017the variables :data:`sys.exc_traceback` (deprecated) and
18:data:`sys.last_traceback` and returned as the third item from
19:func:`sys.exc_info`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000020
21The module defines the following functions:
22
23
Senthil Kumaran11a73892016-01-15 22:13:16 -080024.. function:: print_tb(tb[, limit[, file]])
Georg Brandl8ec7f652007-08-15 14:28:01 +000025
Senthil Kumaran11a73892016-01-15 22:13:16 -080026 Print up to *limit* stack trace entries from the traceback object *tb*. If
27 *limit* is omitted or ``None``, all entries are printed. If *file* is omitted
28 or ``None``, the output goes to ``sys.stderr``; otherwise it should be an
29 open file or file-like object to receive the output.
Georg Brandl8ec7f652007-08-15 14:28:01 +000030
31
Senthil Kumaran11a73892016-01-15 22:13:16 -080032.. function:: print_exception(etype, value, tb[, limit[, file]])
Georg Brandl8ec7f652007-08-15 14:28:01 +000033
Senthil Kumaran11a73892016-01-15 22:13:16 -080034 Print exception information and up to *limit* stack trace entries from the
35 traceback *tb* to *file*. This differs from :func:`print_tb` in the following
36 ways: (1) if *tb* is not ``None``, it prints a header ``Traceback (most
37 recent call last):``; (2) it prints the exception *etype* and *value* after
38 the stack trace; (3) if *etype* is :exc:`SyntaxError` and *value* has the
39 appropriate format, it prints the line where the syntax error occurred with a
40 caret indicating the approximate position of the error.
Georg Brandl8ec7f652007-08-15 14:28:01 +000041
42
43.. function:: print_exc([limit[, file]])
44
45 This is a shorthand for ``print_exception(sys.exc_type, sys.exc_value,
46 sys.exc_traceback, limit, file)``. (In fact, it uses :func:`sys.exc_info` to
47 retrieve the same information in a thread-safe way instead of using the
48 deprecated variables.)
49
50
51.. function:: format_exc([limit])
52
Senthil Kumaran11a73892016-01-15 22:13:16 -080053 This is like ``print_exc(limit)`` but returns a string instead of printing to
54 a file.
Georg Brandl8ec7f652007-08-15 14:28:01 +000055
56 .. versionadded:: 2.4
57
58
59.. function:: print_last([limit[, file]])
60
61 This is a shorthand for ``print_exception(sys.last_type, sys.last_value,
R. David Murrayec047e02009-04-27 17:22:36 +000062 sys.last_traceback, limit, file)``. In general it will work only after
63 an exception has reached an interactive prompt (see :data:`sys.last_type`).
Georg Brandl8ec7f652007-08-15 14:28:01 +000064
65
66.. function:: print_stack([f[, limit[, file]]])
67
Senthil Kumaran11a73892016-01-15 22:13:16 -080068 This function prints a stack trace from its invocation point. The optional
69 *f* argument can be used to specify an alternate stack frame to start. The
Xiang Zhanga948d4f2017-07-12 11:41:33 +080070 optional *limit* and *file* arguments have the same meaning as for
Georg Brandl8ec7f652007-08-15 14:28:01 +000071 :func:`print_exception`.
72
73
Senthil Kumaran11a73892016-01-15 22:13:16 -080074.. function:: extract_tb(tb[, limit])
Georg Brandl8ec7f652007-08-15 14:28:01 +000075
76 Return a list of up to *limit* "pre-processed" stack trace entries extracted
Senthil Kumaran11a73892016-01-15 22:13:16 -080077 from the traceback object *tb*. It is useful for alternate formatting of
78 stack traces. If *limit* is omitted or ``None``, all entries are extracted.
79 A "pre-processed" stack trace entry is a 4-tuple (*filename*, *line number*,
80 function name*, *text*) representing the information that is usually printed
81 for a stack trace. The *text* is a string with leading and trailing
82 whitespace stripped; if the source is not available it is ``None``.
Georg Brandl8ec7f652007-08-15 14:28:01 +000083
84
85.. function:: extract_stack([f[, limit]])
86
87 Extract the raw traceback from the current stack frame. The return value has
88 the same format as for :func:`extract_tb`. The optional *f* and *limit*
89 arguments have the same meaning as for :func:`print_stack`.
90
91
Senthil Kumaran11a73892016-01-15 22:13:16 -080092.. function:: format_list(extracted_list)
Georg Brandl8ec7f652007-08-15 14:28:01 +000093
94 Given a list of tuples as returned by :func:`extract_tb` or
Senthil Kumaran11a73892016-01-15 22:13:16 -080095 :func:`extract_stack`, return a list of strings ready for printing. Each
96 string in the resulting list corresponds to the item with the same index in
97 the argument list. Each string ends in a newline; the strings may contain
98 internal newlines as well, for those items whose source text line is not
99 ``None``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000100
101
Senthil Kumaran11a73892016-01-15 22:13:16 -0800102.. function:: format_exception_only(etype, value)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000103
Senthil Kumaran11a73892016-01-15 22:13:16 -0800104 Format the exception part of a traceback. The arguments are the exception
105 type, *etype* and *value* such as given by ``sys.last_type`` and
106 ``sys.last_value``. The return value is a list of strings, each ending in a
107 newline. Normally, the list contains a single string; however, for
108 :exc:`SyntaxError` exceptions, it contains several lines that (when printed)
109 display detailed information about where the syntax error occurred. The
110 message indicating which exception occurred is the always last string in the
111 list.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000112
113
Senthil Kumaran11a73892016-01-15 22:13:16 -0800114.. function:: format_exception(etype, value, tb[, limit])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000115
116 Format a stack trace and the exception information. The arguments have the
117 same meaning as the corresponding arguments to :func:`print_exception`. The
Senthil Kumaran11a73892016-01-15 22:13:16 -0800118 return value is a list of strings, each ending in a newline and some
119 containing internal newlines. When these lines are concatenated and printed,
120 exactly the same text is printed as does :func:`print_exception`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000121
122
123.. function:: format_tb(tb[, limit])
124
125 A shorthand for ``format_list(extract_tb(tb, limit))``.
126
127
128.. function:: format_stack([f[, limit]])
129
130 A shorthand for ``format_list(extract_stack(f, limit))``.
131
132
133.. function:: tb_lineno(tb)
134
Senthil Kumaran11a73892016-01-15 22:13:16 -0800135 This function returns the current line number set in the traceback object.
136 This function was necessary because in versions of Python prior to 2.3 when
137 the :option:`-O` flag was passed to Python the ``tb.tb_lineno`` was not
138 updated correctly. This function has no use in versions past 2.3.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000139
140
141.. _traceback-example:
142
Georg Brandl722e1012007-12-05 17:56:50 +0000143Traceback Examples
144------------------
Georg Brandl8ec7f652007-08-15 14:28:01 +0000145
146This simple example implements a basic read-eval-print loop, similar to (but
147less useful than) the standard Python interactive interpreter loop. For a more
148complete implementation of the interpreter loop, refer to the :mod:`code`
149module. ::
150
Benjamin Petersona7b55a32009-02-20 03:31:23 +0000151 import sys, traceback
Georg Brandl8ec7f652007-08-15 14:28:01 +0000152
153 def run_user_code(envdir):
154 source = raw_input(">>> ")
155 try:
156 exec source in envdir
157 except:
158 print "Exception in user code:"
159 print '-'*60
160 traceback.print_exc(file=sys.stdout)
161 print '-'*60
162
163 envdir = {}
164 while 1:
165 run_user_code(envdir)
166
Georg Brandl722e1012007-12-05 17:56:50 +0000167
168The following example demonstrates the different ways to print and format the
169exception and traceback::
170
Benjamin Petersona7b55a32009-02-20 03:31:23 +0000171 import sys, traceback
Georg Brandl722e1012007-12-05 17:56:50 +0000172
173 def lumberjack():
174 bright_side_of_death()
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000175
Georg Brandl722e1012007-12-05 17:56:50 +0000176 def bright_side_of_death():
177 return tuple()[0]
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000178
Georg Brandl722e1012007-12-05 17:56:50 +0000179 try:
180 lumberjack()
Ezio Melotti93dd9b82010-03-13 01:21:34 +0000181 except IndexError:
182 exc_type, exc_value, exc_traceback = sys.exc_info()
Georg Brandl722e1012007-12-05 17:56:50 +0000183 print "*** print_tb:"
Ezio Melotti93dd9b82010-03-13 01:21:34 +0000184 traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
Georg Brandl722e1012007-12-05 17:56:50 +0000185 print "*** print_exception:"
Ezio Melotti93dd9b82010-03-13 01:21:34 +0000186 traceback.print_exception(exc_type, exc_value, exc_traceback,
Georg Brandl722e1012007-12-05 17:56:50 +0000187 limit=2, file=sys.stdout)
188 print "*** print_exc:"
189 traceback.print_exc()
190 print "*** format_exc, first and last line:"
191 formatted_lines = traceback.format_exc().splitlines()
192 print formatted_lines[0]
193 print formatted_lines[-1]
194 print "*** format_exception:"
Ezio Melotti93dd9b82010-03-13 01:21:34 +0000195 print repr(traceback.format_exception(exc_type, exc_value,
196 exc_traceback))
Georg Brandl722e1012007-12-05 17:56:50 +0000197 print "*** extract_tb:"
Ezio Melotti93dd9b82010-03-13 01:21:34 +0000198 print repr(traceback.extract_tb(exc_traceback))
Georg Brandl722e1012007-12-05 17:56:50 +0000199 print "*** format_tb:"
Ezio Melotti93dd9b82010-03-13 01:21:34 +0000200 print repr(traceback.format_tb(exc_traceback))
201 print "*** tb_lineno:", exc_traceback.tb_lineno
Georg Brandl722e1012007-12-05 17:56:50 +0000202
203
204The output for the example would look similar to this::
205
206 *** print_tb:
R. David Murrayec047e02009-04-27 17:22:36 +0000207 File "<doctest...>", line 10, in <module>
Georg Brandl722e1012007-12-05 17:56:50 +0000208 lumberjack()
209 *** print_exception:
210 Traceback (most recent call last):
R. David Murrayec047e02009-04-27 17:22:36 +0000211 File "<doctest...>", line 10, in <module>
Georg Brandl722e1012007-12-05 17:56:50 +0000212 lumberjack()
R. David Murrayec047e02009-04-27 17:22:36 +0000213 File "<doctest...>", line 4, in lumberjack
Georg Brandl722e1012007-12-05 17:56:50 +0000214 bright_side_of_death()
215 IndexError: tuple index out of range
216 *** print_exc:
217 Traceback (most recent call last):
R. David Murrayec047e02009-04-27 17:22:36 +0000218 File "<doctest...>", line 10, in <module>
Georg Brandl722e1012007-12-05 17:56:50 +0000219 lumberjack()
R. David Murrayec047e02009-04-27 17:22:36 +0000220 File "<doctest...>", line 4, in lumberjack
Georg Brandl722e1012007-12-05 17:56:50 +0000221 bright_side_of_death()
222 IndexError: tuple index out of range
223 *** format_exc, first and last line:
224 Traceback (most recent call last):
225 IndexError: tuple index out of range
226 *** format_exception:
227 ['Traceback (most recent call last):\n',
R. David Murrayec047e02009-04-27 17:22:36 +0000228 ' File "<doctest...>", line 10, in <module>\n lumberjack()\n',
229 ' File "<doctest...>", line 4, in lumberjack\n bright_side_of_death()\n',
230 ' File "<doctest...>", line 7, in bright_side_of_death\n return tuple()[0]\n',
Georg Brandl722e1012007-12-05 17:56:50 +0000231 'IndexError: tuple index out of range\n']
232 *** extract_tb:
R. David Murrayec047e02009-04-27 17:22:36 +0000233 [('<doctest...>', 10, '<module>', 'lumberjack()'),
234 ('<doctest...>', 4, 'lumberjack', 'bright_side_of_death()'),
R. David Murray3b23c9c2009-04-28 19:02:55 +0000235 ('<doctest...>', 7, 'bright_side_of_death', 'return tuple()[0]')]
Georg Brandl722e1012007-12-05 17:56:50 +0000236 *** format_tb:
R. David Murrayec047e02009-04-27 17:22:36 +0000237 [' File "<doctest...>", line 10, in <module>\n lumberjack()\n',
238 ' File "<doctest...>", line 4, in lumberjack\n bright_side_of_death()\n',
239 ' File "<doctest...>", line 7, in bright_side_of_death\n return tuple()[0]\n']
240 *** tb_lineno: 10
Georg Brandl722e1012007-12-05 17:56:50 +0000241
R. David Murray3b23c9c2009-04-28 19:02:55 +0000242
Georg Brandl722e1012007-12-05 17:56:50 +0000243The following example shows the different ways to print and format the stack::
244
245 >>> import traceback
246 >>> def another_function():
247 ... lumberstack()
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000248 ...
Georg Brandl722e1012007-12-05 17:56:50 +0000249 >>> def lumberstack():
250 ... traceback.print_stack()
251 ... print repr(traceback.extract_stack())
252 ... print repr(traceback.format_stack())
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000253 ...
Georg Brandl722e1012007-12-05 17:56:50 +0000254 >>> 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()'),
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']
267
268
R. David Murrayec047e02009-04-27 17:22:36 +0000269This last example demonstrates the final few formatting functions:
270
271.. doctest::
272 :options: +NORMALIZE_WHITESPACE
Georg Brandl722e1012007-12-05 17:56:50 +0000273
274 >>> import traceback
Georg Brandle1b79ce2009-04-27 15:09:25 +0000275 >>> traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'),
276 ... ('eggs.py', 42, 'eggs', 'return "bacon"')])
Georg Brandl722e1012007-12-05 17:56:50 +0000277 [' File "spam.py", line 3, in <module>\n spam.eggs()\n',
278 ' File "eggs.py", line 42, in eggs\n return "bacon"\n']
Georg Brandle1b79ce2009-04-27 15:09:25 +0000279 >>> an_error = IndexError('tuple index out of range')
280 >>> traceback.format_exception_only(type(an_error), an_error)
Georg Brandl722e1012007-12-05 17:56:50 +0000281 ['IndexError: tuple index out of range\n']