blob: 29b09ae5313c3a78125c1a4f60fc7a8e380aada8 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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 variables ``sys.exc_traceback`` (deprecated) and ``sys.last_traceback`` and
19returned as the third item from :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_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
53 This is like ``print_exc(limit)`` but returns a string instead of printing to a
54 file.
55
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,
62 sys.last_traceback, limit, file)``.
63
64
65.. function:: print_stack([f[, limit[, file]]])
66
67 This function prints a stack trace from its invocation point. The optional *f*
68 argument can be used to specify an alternate stack frame to start. The optional
69 *limit* and *file* arguments have the same meaning as for
70 :func:`print_exception`.
71
72
73.. function:: extract_tb(traceback[, limit])
74
75 Return a list of up to *limit* "pre-processed" stack trace entries extracted
76 from the traceback object *traceback*. It is useful for alternate formatting of
77 stack traces. If *limit* is omitted or ``None``, all entries are extracted. A
78 "pre-processed" stack trace entry is a quadruple (*filename*, *line number*,
79 *function name*, *text*) representing the information that is usually printed
80 for a stack trace. The *text* is a string with leading and trailing whitespace
81 stripped; if the source is not available it is ``None``.
82
83
84.. function:: extract_stack([f[, limit]])
85
86 Extract the raw traceback from the current stack frame. The return value has
87 the same format as for :func:`extract_tb`. The optional *f* and *limit*
88 arguments have the same meaning as for :func:`print_stack`.
89
90
91.. function:: format_list(list)
92
93 Given a list of tuples as returned by :func:`extract_tb` or
94 :func:`extract_stack`, return a list of strings ready for printing. Each string
95 in the resulting list corresponds to the item with the same index in the
96 argument list. Each string ends in a newline; the strings may contain internal
97 newlines as well, for those items whose source text line is not ``None``.
98
99
100.. function:: format_exception_only(type, value)
101
102 Format the exception part of a traceback. The arguments are the exception type
103 and value such as given by ``sys.last_type`` and ``sys.last_value``. The return
104 value is a list of strings, each ending in a newline. Normally, the list
105 contains a single string; however, for :exc:`SyntaxError` exceptions, it
106 contains several lines that (when printed) display detailed information about
107 where the syntax error occurred. The message indicating which exception
108 occurred is the always last string in the list.
109
110
111.. function:: format_exception(type, value, tb[, limit])
112
113 Format a stack trace and the exception information. The arguments have the
114 same meaning as the corresponding arguments to :func:`print_exception`. The
115 return value is a list of strings, each ending in a newline and some containing
116 internal newlines. When these lines are concatenated and printed, exactly the
117 same text is printed as does :func:`print_exception`.
118
119
120.. function:: format_tb(tb[, limit])
121
122 A shorthand for ``format_list(extract_tb(tb, limit))``.
123
124
125.. function:: format_stack([f[, limit]])
126
127 A shorthand for ``format_list(extract_stack(f, limit))``.
128
129
130.. function:: tb_lineno(tb)
131
132 This function returns the current line number set in the traceback object. This
133 function was necessary because in versions of Python prior to 2.3 when the
134 :option:`-O` flag was passed to Python the ``tb.tb_lineno`` was not updated
135 correctly. This function has no use in versions past 2.3.
136
137
138.. _traceback-example:
139
Georg Brandl722e1012007-12-05 17:56:50 +0000140Traceback Examples
141------------------
Georg Brandl8ec7f652007-08-15 14:28:01 +0000142
143This simple example implements a basic read-eval-print loop, similar to (but
144less useful than) the standard Python interactive interpreter loop. For a more
145complete implementation of the interpreter loop, refer to the :mod:`code`
146module. ::
147
Jeroen Ruigrok van der Werven51497422009-02-19 18:52:21 +0000148 import sys
149 import traceback
Georg Brandl8ec7f652007-08-15 14:28:01 +0000150
151 def run_user_code(envdir):
152 source = raw_input(">>> ")
153 try:
154 exec source in envdir
155 except:
156 print "Exception in user code:"
157 print '-'*60
158 traceback.print_exc(file=sys.stdout)
159 print '-'*60
160
161 envdir = {}
162 while 1:
163 run_user_code(envdir)
164
Georg Brandl722e1012007-12-05 17:56:50 +0000165
166The following example demonstrates the different ways to print and format the
167exception and traceback::
168
Jeroen Ruigrok van der Werven51497422009-02-19 18:52:21 +0000169 import sys
170 import traceback
Georg Brandl722e1012007-12-05 17:56:50 +0000171
172 def lumberjack():
173 bright_side_of_death()
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000174
Georg Brandl722e1012007-12-05 17:56:50 +0000175 def bright_side_of_death():
176 return tuple()[0]
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000177
Georg Brandl722e1012007-12-05 17:56:50 +0000178 try:
179 lumberjack()
180 except:
181 exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
182 print "*** print_tb:"
183 traceback.print_tb(exceptionTraceback, limit=1, file=sys.stdout)
184 print "*** print_exception:"
185 traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
186 limit=2, file=sys.stdout)
187 print "*** print_exc:"
188 traceback.print_exc()
189 print "*** format_exc, first and last line:"
190 formatted_lines = traceback.format_exc().splitlines()
191 print formatted_lines[0]
192 print formatted_lines[-1]
193 print "*** format_exception:"
194 print repr(traceback.format_exception(exceptionType, exceptionValue,
195 exceptionTraceback))
196 print "*** extract_tb:"
197 print repr(traceback.extract_tb(exceptionTraceback))
198 print "*** format_tb:"
199 print repr(traceback.format_tb(exceptionTraceback))
200 print "*** tb_lineno:", traceback.tb_lineno(exceptionTraceback)
201 print "*** print_last:"
202 traceback.print_last()
203
204
205The output for the example would look similar to this::
206
207 *** print_tb:
208 File "<doctest>", line 9, in <module>
209 lumberjack()
210 *** print_exception:
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 *** print_exc:
218 Traceback (most recent call last):
219 File "<doctest>", line 9, in <module>
220 lumberjack()
221 File "<doctest>", line 3, in lumberjack
222 bright_side_of_death()
223 IndexError: tuple index out of range
224 *** format_exc, first and last line:
225 Traceback (most recent call last):
226 IndexError: tuple index out of range
227 *** format_exception:
228 ['Traceback (most recent call last):\n',
229 ' File "<doctest>", line 9, in <module>\n lumberjack()\n',
230 ' File "<doctest>", line 3, in lumberjack\n bright_side_of_death()\n',
231 ' File "<doctest>", line 6, in bright_side_of_death\n return tuple()[0]\n',
232 'IndexError: tuple index out of range\n']
233 *** extract_tb:
234 [('<doctest>', 9, '<module>', 'lumberjack()'),
235 ('<doctest>', 3, 'lumberjack', 'bright_side_of_death()'),
236 ('<doctest>', 6, 'bright_side_of_death', 'return tuple()[0]')]
237 *** format_tb:
238 [' File "<doctest>", line 9, in <module>\n lumberjack()\n',
239 ' File "<doctest>", line 3, in lumberjack\n bright_side_of_death()\n',
240 ' File "<doctest>", line 6, in bright_side_of_death\n return tuple()[0]\n']
241 *** tb_lineno: 2
242 *** print_last:
243 Traceback (most recent call last):
244 File "<doctest>", line 9, in <module>
245 lumberjack()
246 File "<doctest>", line 3, in lumberjack
247 bright_side_of_death()
248 IndexError: tuple index out of range
249
250
251The following example shows the different ways to print and format the stack::
252
253 >>> import traceback
254 >>> def another_function():
255 ... lumberstack()
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000256 ...
Georg Brandl722e1012007-12-05 17:56:50 +0000257 >>> def lumberstack():
258 ... traceback.print_stack()
259 ... print repr(traceback.extract_stack())
260 ... print repr(traceback.format_stack())
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000261 ...
Georg Brandl722e1012007-12-05 17:56:50 +0000262 >>> another_function()
263 File "<doctest>", line 10, in <module>
264 another_function()
265 File "<doctest>", line 3, in another_function
266 lumberstack()
267 File "<doctest>", line 6, in lumberstack
268 traceback.print_stack()
269 [('<doctest>', 10, '<module>', 'another_function()'),
270 ('<doctest>', 3, 'another_function', 'lumberstack()'),
271 ('<doctest>', 7, 'lumberstack', 'print repr(traceback.extract_stack())')]
272 [' File "<doctest>", line 10, in <module>\n another_function()\n',
273 ' File "<doctest>", line 3, in another_function\n lumberstack()\n',
274 ' File "<doctest>", line 8, in lumberstack\n print repr(traceback.format_stack())\n']
275
276
277This last example demonstrates the final few formatting functions::
278
279 >>> import traceback
280 >>> format_list([('spam.py', 3, '<module>', 'spam.eggs()'),
281 ... ('eggs.py', 42, 'eggs', 'return "bacon"')])
282 [' File "spam.py", line 3, in <module>\n spam.eggs()\n',
283 ' File "eggs.py", line 42, in eggs\n return "bacon"\n']
284 >>> theError = IndexError('tuple indx out of range')
285 >>> traceback.format_exception_only(type(theError), theError)
286 ['IndexError: tuple index out of range\n']