blob: 179e04eea979c334e840b3ad8c01c5fde77b1325 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`traceback` --- Print or retrieve a stack traceback
3========================================================
4
5.. module:: traceback
6 :synopsis: Print or retrieve a stack traceback.
7
8
9This module provides a standard interface to extract, format and print stack
10traces of Python programs. It exactly mimics the behavior of the Python
11interpreter when it prints a stack trace. This is useful when you want to print
12stack traces under program control, such as in a "wrapper" around the
13interpreter.
14
15.. index:: object: traceback
16
17The module uses traceback objects --- this is the object type that is stored in
18the ``sys.last_traceback`` variable and returned as the third item from
19:func:`sys.exc_info`.
20
21The module defines the following functions:
22
23
24.. function:: print_tb(traceback[, limit[, file]])
25
26 Print up to *limit* stack trace entries from *traceback*. If *limit* is omitted
27 or ``None``, all entries are printed. If *file* is omitted or ``None``, the
28 output goes to ``sys.stderr``; otherwise it should be an open file or file-like
29 object to receive the output.
30
31
32.. function:: print_exception(type, value, traceback[, limit[, file]])
33
34 Print exception information and up to *limit* stack trace entries from
35 *traceback* to *file*. This differs from :func:`print_tb` in the following ways:
36 (1) if *traceback* is not ``None``, it prints a header ``Traceback (most recent
37 call last):``; (2) it prints the exception *type* and *value* after the stack
38 trace; (3) if *type* is :exc:`SyntaxError` and *value* has the appropriate
39 format, it prints the line where the syntax error occurred with a caret
40 indicating the approximate position of the error.
41
42
43.. function:: print_exc([limit[, file]])
44
45 This is a shorthand for ``print_exception(*sys.exc_info()``.
46
47
48.. function:: format_exc([limit])
49
50 This is like ``print_exc(limit)`` but returns a string instead of printing to a
51 file.
52
Georg Brandl116aa622007-08-15 14:28:22 +000053
54.. function:: print_last([limit[, file]])
55
56 This is a shorthand for ``print_exception(sys.last_type, sys.last_value,
57 sys.last_traceback, limit, file)``.
58
59
60.. function:: print_stack([f[, limit[, file]]])
61
62 This function prints a stack trace from its invocation point. The optional *f*
63 argument can be used to specify an alternate stack frame to start. The optional
64 *limit* and *file* arguments have the same meaning as for
65 :func:`print_exception`.
66
67
68.. function:: extract_tb(traceback[, limit])
69
70 Return a list of up to *limit* "pre-processed" stack trace entries extracted
71 from the traceback object *traceback*. It is useful for alternate formatting of
72 stack traces. If *limit* is omitted or ``None``, all entries are extracted. A
73 "pre-processed" stack trace entry is a quadruple (*filename*, *line number*,
74 *function name*, *text*) representing the information that is usually printed
75 for a stack trace. The *text* is a string with leading and trailing whitespace
76 stripped; if the source is not available it is ``None``.
77
78
79.. function:: extract_stack([f[, limit]])
80
81 Extract the raw traceback from the current stack frame. The return value has
82 the same format as for :func:`extract_tb`. The optional *f* and *limit*
83 arguments have the same meaning as for :func:`print_stack`.
84
85
86.. function:: format_list(list)
87
88 Given a list of tuples as returned by :func:`extract_tb` or
89 :func:`extract_stack`, return a list of strings ready for printing. Each string
90 in the resulting list corresponds to the item with the same index in the
91 argument list. Each string ends in a newline; the strings may contain internal
92 newlines as well, for those items whose source text line is not ``None``.
93
94
95.. function:: format_exception_only(type, value)
96
97 Format the exception part of a traceback. The arguments are the exception type
98 and value such as given by ``sys.last_type`` and ``sys.last_value``. The return
99 value is a list of strings, each ending in a newline. Normally, the list
100 contains a single string; however, for :exc:`SyntaxError` exceptions, it
101 contains several lines that (when printed) display detailed information about
102 where the syntax error occurred. The message indicating which exception
103 occurred is the always last string in the list.
104
105
106.. function:: format_exception(type, value, tb[, limit])
107
108 Format a stack trace and the exception information. The arguments have the
109 same meaning as the corresponding arguments to :func:`print_exception`. The
110 return value is a list of strings, each ending in a newline and some containing
111 internal newlines. When these lines are concatenated and printed, exactly the
112 same text is printed as does :func:`print_exception`.
113
114
115.. function:: format_tb(tb[, limit])
116
117 A shorthand for ``format_list(extract_tb(tb, limit))``.
118
119
120.. function:: format_stack([f[, limit]])
121
122 A shorthand for ``format_list(extract_stack(f, limit))``.
123
124
125.. function:: tb_lineno(tb)
126
127 This function returns the current line number set in the traceback object. This
128 function was necessary because in versions of Python prior to 2.3 when the
129 :option:`-O` flag was passed to Python the ``tb.tb_lineno`` was not updated
130 correctly. This function has no use in versions past 2.3.
131
132
133.. _traceback-example:
134
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000135Traceback Examples
136------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138This simple example implements a basic read-eval-print loop, similar to (but
139less useful than) the standard Python interactive interpreter loop. For a more
140complete implementation of the interpreter loop, refer to the :mod:`code`
141module. ::
142
143 import sys, traceback
144
145 def run_user_code(envdir):
Georg Brandl8d5c3922007-12-02 22:48:17 +0000146 source = input(">>> ")
Georg Brandl116aa622007-08-15 14:28:22 +0000147 try:
148 exec(source, envdir)
149 except:
Collin Winterc79461b2007-09-01 23:34:30 +0000150 print("Exception in user code:")
151 print("-"*60)
Georg Brandl116aa622007-08-15 14:28:22 +0000152 traceback.print_exc(file=sys.stdout)
Collin Winterc79461b2007-09-01 23:34:30 +0000153 print("-"*60)
Georg Brandl116aa622007-08-15 14:28:22 +0000154
155 envdir = {}
Collin Winterc79461b2007-09-01 23:34:30 +0000156 while True:
Georg Brandl116aa622007-08-15 14:28:22 +0000157 run_user_code(envdir)
158
Christian Heimesb9eccbf2007-12-05 20:18:38 +0000159
160The following example demonstrates the different ways to print and format the
161exception and traceback::
162
163 import sys, traceback
164
165 def lumberjack():
166 bright_side_of_death()
167
168 def bright_side_of_death():
169 return tuple()[0]
170
171 try:
172 lumberjack()
173 except:
174 exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
175 print "*** print_tb:"
176 traceback.print_tb(exceptionTraceback, limit=1, file=sys.stdout)
177 print "*** print_exception:"
178 traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
179 limit=2, file=sys.stdout)
180 print "*** print_exc:"
181 traceback.print_exc()
182 print "*** format_exc, first and last line:"
183 formatted_lines = traceback.format_exc().splitlines()
184 print formatted_lines[0]
185 print formatted_lines[-1]
186 print "*** format_exception:"
187 print repr(traceback.format_exception(exceptionType, exceptionValue,
188 exceptionTraceback))
189 print "*** extract_tb:"
190 print repr(traceback.extract_tb(exceptionTraceback))
191 print "*** format_tb:"
192 print repr(traceback.format_tb(exceptionTraceback))
193 print "*** tb_lineno:", traceback.tb_lineno(exceptionTraceback)
194 print "*** print_last:"
195 traceback.print_last()
196
197
198The output for the example would look similar to this::
199
200 *** print_tb:
201 File "<doctest>", line 9, in <module>
202 lumberjack()
203 *** print_exception:
204 Traceback (most recent call last):
205 File "<doctest>", line 9, in <module>
206 lumberjack()
207 File "<doctest>", line 3, in lumberjack
208 bright_side_of_death()
209 IndexError: tuple index out of range
210 *** print_exc:
211 Traceback (most recent call last):
212 File "<doctest>", line 9, in <module>
213 lumberjack()
214 File "<doctest>", line 3, in lumberjack
215 bright_side_of_death()
216 IndexError: tuple index out of range
217 *** format_exc, first and last line:
218 Traceback (most recent call last):
219 IndexError: tuple index out of range
220 *** format_exception:
221 ['Traceback (most recent call last):\n',
222 ' File "<doctest>", line 9, in <module>\n lumberjack()\n',
223 ' File "<doctest>", line 3, in lumberjack\n bright_side_of_death()\n',
224 ' File "<doctest>", line 6, in bright_side_of_death\n return tuple()[0]\n',
225 'IndexError: tuple index out of range\n']
226 *** extract_tb:
227 [('<doctest>', 9, '<module>', 'lumberjack()'),
228 ('<doctest>', 3, 'lumberjack', 'bright_side_of_death()'),
229 ('<doctest>', 6, 'bright_side_of_death', 'return tuple()[0]')]
230 *** format_tb:
231 [' File "<doctest>", line 9, in <module>\n lumberjack()\n',
232 ' File "<doctest>", line 3, in lumberjack\n bright_side_of_death()\n',
233 ' File "<doctest>", line 6, in bright_side_of_death\n return tuple()[0]\n']
234 *** tb_lineno: 2
235 *** print_last:
236 Traceback (most recent call last):
237 File "<doctest>", line 9, in <module>
238 lumberjack()
239 File "<doctest>", line 3, in lumberjack
240 bright_side_of_death()
241 IndexError: tuple index out of range
242
243
244The following example shows the different ways to print and format the stack::
245
246 >>> import traceback
247 >>> def another_function():
248 ... lumberstack()
249 ...
250 >>> def lumberstack():
251 ... traceback.print_stack()
252 ... print repr(traceback.extract_stack())
253 ... print repr(traceback.format_stack())
254 ...
255 >>> another_function()
256 File "<doctest>", line 10, in <module>
257 another_function()
258 File "<doctest>", line 3, in another_function
259 lumberstack()
260 File "<doctest>", line 6, in lumberstack
261 traceback.print_stack()
262 [('<doctest>', 10, '<module>', 'another_function()'),
263 ('<doctest>', 3, 'another_function', 'lumberstack()'),
264 ('<doctest>', 7, 'lumberstack', 'print repr(traceback.extract_stack())')]
265 [' File "<doctest>", line 10, in <module>\n another_function()\n',
266 ' File "<doctest>", line 3, in another_function\n lumberstack()\n',
267 ' File "<doctest>", line 8, in lumberstack\n print repr(traceback.format_stack())\n']
268
269
270This last example demonstrates the final few formatting functions::
271
272 >>> import traceback
273 >>> format_list([('spam.py', 3, '<module>', 'spam.eggs()'),
274 ... ('eggs.py', 42, 'eggs', 'return "bacon"')])
275 [' File "spam.py", line 3, in <module>\n spam.eggs()\n',
276 ' File "eggs.py", line 42, in eggs\n return "bacon"\n']
277 >>> theError = IndexError('tuple indx out of range')
278 >>> traceback.format_exception_only(type(theError), theError)
279 ['IndexError: tuple index out of range\n']