~dkuhlman/python-training-materials/Materials

« back to all changes in this revision

Viewing changes to python-3.5.1-docs-html/_sources/library/traceback.txt

  • Committer: Dave Kuhlman
  • Date: 2016-02-11 21:17:09 UTC
  • Revision ID: dkuhlman@davekuhlman.org-20160211211709-03yaen3cjempbi2m
Updated Python 2.7 docs; added Python 3.5 docs

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
:mod:`traceback` --- Print or retrieve a stack traceback
 
2
========================================================
 
3
 
 
4
.. module:: traceback
 
5
   :synopsis: Print or retrieve a stack traceback.
 
6
 
 
7
 
 
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
 
12
interpreter.
 
13
 
 
14
.. index:: object: traceback
 
15
 
 
16
The module uses traceback objects --- this is the object type that is stored in
 
17
the :data:`sys.last_traceback` variable and returned as the third item from
 
18
:func:`sys.exc_info`.
 
19
 
 
20
The module defines the following functions:
 
21
 
 
22
 
 
23
.. function:: print_tb(tb, limit=None, file=None)
 
24
 
 
25
   Print up to *limit* stack trace entries from traceback object *tb* (starting
 
26
   from the caller's frame) if *limit* is positive.  Otherwise, print the last
 
27
   ``abs(limit)`` entries.  If *limit* is omitted or ``None``, all entries are
 
28
   printed.  If *file* is omitted or ``None``, the output goes to
 
29
   ``sys.stderr``; otherwise it should be an open file or file-like object to
 
30
   receive the output.
 
31
 
 
32
   .. versionchanged:: 3.5
 
33
       Added negative *limit* support.
 
34
 
 
35
 
 
36
.. function:: print_exception(etype, value, tb, limit=None, file=None, chain=True)
 
37
 
 
38
   Print exception information and stack trace entries from traceback object
 
39
   *tb* to *file*. This differs from :func:`print_tb` in the following
 
40
   ways:
 
41
 
 
42
   * if *tb* is not ``None``, it prints a header ``Traceback (most recent
 
43
     call last):``
 
44
   * it prints the exception *etype* and *value* after the stack trace
 
45
   * if *etype* is :exc:`SyntaxError` and *value* has the appropriate format, it
 
46
     prints the line where the syntax error occurred with a caret indicating the
 
47
     approximate position of the error.
 
48
 
 
49
   The optional *limit* argument has the same meaning as for :func:`print_tb`.
 
50
   If *chain* is true (the default), then chained exceptions (the
 
51
   :attr:`__cause__` or :attr:`__context__` attributes of the exception) will be
 
52
   printed as well, like the interpreter itself does when printing an unhandled
 
53
   exception.
 
54
 
 
55
 
 
56
.. function:: print_exc(limit=None, file=None, chain=True)
 
57
 
 
58
   This is a shorthand for ``print_exception(*sys.exc_info(), limit, file,
 
59
   chain)``.
 
60
 
 
61
 
 
62
.. function:: print_last(limit=None, file=None, chain=True)
 
63
 
 
64
   This is a shorthand for ``print_exception(sys.last_type, sys.last_value,
 
65
   sys.last_traceback, limit, file, chain)``.  In general it will work only
 
66
   after an exception has reached an interactive prompt (see
 
67
   :data:`sys.last_type`).
 
68
 
 
69
 
 
70
.. function:: print_stack(f=None, limit=None, file=None)
 
71
 
 
72
   Print up to *limit* stack trace entries (starting from the invocation
 
73
   point) if *limit* is positive.  Otherwise, print the last ``abs(limit)``
 
74
   entries.  If *limit* is omitted or ``None``, all entries are printed.
 
75
   The optional *f* argument can be used to specify an alternate stack frame
 
76
   to start.  The optional *file* argument has the same meaning as for
 
77
   :func:`print_tb`.
 
78
 
 
79
   .. versionchanged:: 3.5
 
80
          Added negative *limit* support.
 
81
 
 
82
 
 
83
.. function:: extract_tb(tb, limit=None)
 
84
 
 
85
   Return a list of "pre-processed" stack trace entries extracted from the
 
86
   traceback object *tb*.  It is useful for alternate formatting of
 
87
   stack traces.  The optional *limit* argument has the same meaning as for
 
88
   :func:`print_tb`.  A "pre-processed" stack trace entry is a 4-tuple
 
89
   (*filename*, *line number*, *function name*, *text*) representing the
 
90
   information that is usually printed for a stack trace.  The *text* is a
 
91
   string with leading and trailing whitespace stripped; if the source is
 
92
   not available it is ``None``.
 
93
 
 
94
 
 
95
.. function:: extract_stack(f=None, limit=None)
 
96
 
 
97
   Extract the raw traceback from the current stack frame.  The return value has
 
98
   the same format as for :func:`extract_tb`.  The optional *f* and *limit*
 
99
   arguments have the same meaning as for :func:`print_stack`.
 
100
 
 
101
 
 
102
.. function:: format_list(extracted_list)
 
103
 
 
104
   Given a list of tuples as returned by :func:`extract_tb` or
 
105
   :func:`extract_stack`, return a list of strings ready for printing. Each
 
106
   string in the resulting list corresponds to the item with the same index in
 
107
   the argument list.  Each string ends in a newline; the strings may contain
 
108
   internal newlines as well, for those items whose source text line is not
 
109
   ``None``.
 
110
 
 
111
 
 
112
.. function:: format_exception_only(etype, value)
 
113
 
 
114
   Format the exception part of a traceback.  The arguments are the exception
 
115
   type and value such as given by ``sys.last_type`` and ``sys.last_value``.
 
116
   The return value is a list of strings, each ending in a newline.  Normally,
 
117
   the list contains a single string; however, for :exc:`SyntaxError`
 
118
   exceptions, it contains several lines that (when printed) display detailed
 
119
   information about where the syntax error occurred.  The message indicating
 
120
   which exception occurred is the always last string in the list.
 
121
 
 
122
 
 
123
.. function:: format_exception(etype, value, tb, limit=None, chain=True)
 
124
 
 
125
   Format a stack trace and the exception information.  The arguments  have the
 
126
   same meaning as the corresponding arguments to :func:`print_exception`.  The
 
127
   return value is a list of strings, each ending in a newline and some
 
128
   containing internal newlines.  When these lines are concatenated and printed,
 
129
   exactly the same text is printed as does :func:`print_exception`.
 
130
 
 
131
 
 
132
.. function:: format_exc(limit=None, chain=True)
 
133
 
 
134
   This is like ``print_exc(limit)`` but returns a string instead of printing to
 
135
   a file.
 
136
 
 
137
 
 
138
.. function:: format_tb(tb, limit=None)
 
139
 
 
140
   A shorthand for ``format_list(extract_tb(tb, limit))``.
 
141
 
 
142
 
 
143
.. function:: format_stack(f=None, limit=None)
 
144
 
 
145
   A shorthand for ``format_list(extract_stack(f, limit))``.
 
146
 
 
147
.. function:: clear_frames(tb)
 
148
 
 
149
   Clears the local variables of all the stack frames in a traceback *tb*
 
150
   by calling the :meth:`clear` method of each frame object.
 
151
 
 
152
   .. versionadded:: 3.4
 
153
 
 
154
.. function:: walk_stack(f)
 
155
 
 
156
   Walk a stack following ``f.f_back`` from the given frame, yielding the frame
 
157
   and line number for each frame. If *f* is ``None``, the current stack is
 
158
   used. This helper is used with :meth:`StackSummary.extract`.
 
159
 
 
160
   .. versionadded:: 3.5
 
161
 
 
162
.. function:: walk_tb(tb)
 
163
 
 
164
   Walk a traceback following ``tb_next`` yielding the frame and line number
 
165
   for each frame. This helper is used with :meth:`StackSummary.extract`.
 
166
 
 
167
   .. versionadded:: 3.5
 
168
 
 
169
The module also defines the following classes:
 
170
 
 
171
:class:`TracebackException` Objects
 
172
-----------------------------------
 
173
 
 
174
.. versionadded:: 3.5
 
175
 
 
176
:class:`TracebackException` objects are created from actual exceptions to
 
177
capture data for later printing in a lightweight fashion.
 
178
 
 
179
.. class:: TracebackException(exc_type, exc_value, exc_traceback, *, limit=None, lookup_lines=True, capture_locals=False)
 
180
 
 
181
   Capture an exception for later rendering. *limit*, *lookup_lines* and
 
182
   *capture_locals* are as for the :class:`StackSummary` class.
 
183
 
 
184
   Note that when locals are captured, they are also shown in the traceback.
 
185
 
 
186
   .. attribute:: __cause__
 
187
 
 
188
      A :class:`TracebackException` of the original ``__cause__``.
 
189
 
 
190
   .. attribute:: __context__
 
191
 
 
192
      A :class:`TracebackException` of the original ``__context__``.
 
193
 
 
194
   .. attribute:: __suppress_context__
 
195
 
 
196
      The ``__suppress_context__`` value from the original exception.
 
197
 
 
198
   .. attribute:: stack
 
199
 
 
200
      A :class:`StackSummary` representing the traceback.
 
201
 
 
202
   .. attribute:: exc_type
 
203
 
 
204
      The class of the original traceback.
 
205
 
 
206
   .. attribute:: filename
 
207
 
 
208
      For syntax errors - the file name where the error occurred.
 
209
 
 
210
   .. attribute:: lineno
 
211
 
 
212
      For syntax errors - the line number where the error occurred.
 
213
 
 
214
   .. attribute:: text
 
215
 
 
216
      For syntax errors - the text where the error occurred.
 
217
 
 
218
   .. attribute:: offset
 
219
 
 
220
      For syntax errors - the offset into the text where the error occurred.
 
221
 
 
222
   .. attribute:: msg
 
223
 
 
224
      For syntax errors - the compiler error message.
 
225
 
 
226
   .. classmethod:: from_exception(exc, *, limit=None, lookup_lines=True, capture_locals=False)
 
227
 
 
228
      Capture an exception for later rendering. *limit*, *lookup_lines* and
 
229
      *capture_locals* are as for the :class:`StackSummary` class.
 
230
 
 
231
      Note that when locals are captured, they are also shown in the traceback.
 
232
 
 
233
   .. method:: format(*, chain=True)
 
234
 
 
235
      Format the exception.
 
236
 
 
237
      If *chain* is not ``True``, ``__cause__`` and ``__context__`` will not
 
238
      be formatted.
 
239
 
 
240
      The return value is a generator of strings, each ending in a newline and
 
241
      some containing internal newlines. :func:`~traceback.print_exception`
 
242
      is a wrapper around this method which just prints the lines to a file.
 
243
 
 
244
      The message indicating which exception occurred is always the last
 
245
      string in the output.
 
246
 
 
247
   .. method::  format_exception_only()
 
248
 
 
249
      Format the exception part of the traceback.
 
250
 
 
251
      The return value is a generator of strings, each ending in a newline.
 
252
 
 
253
      Normally, the generator emits a single string; however, for
 
254
      :exc:`SyntaxError` exceptions, it emits several lines that (when
 
255
      printed) display detailed information about where the syntax
 
256
      error occurred.
 
257
 
 
258
      The message indicating which exception occurred is always the last
 
259
      string in the output.
 
260
 
 
261
 
 
262
:class:`StackSummary` Objects
 
263
-----------------------------
 
264
 
 
265
.. versionadded:: 3.5
 
266
 
 
267
:class:`StackSummary` objects represent a call stack ready for formatting.
 
268
 
 
269
.. class:: StackSummary
 
270
 
 
271
   .. classmethod:: extract(frame_gen, *, limit=None, lookup_lines=True, capture_locals=False)
 
272
 
 
273
      Construct a :class:`StackSummary` object from a frame generator (such as
 
274
      is returned by :func:`~traceback.walk_stack` or
 
275
      :func:`~traceback.walk_tb`).
 
276
 
 
277
      If *limit* is supplied, only this many frames are taken from *frame_gen*.
 
278
      If *lookup_lines* is ``False``, the returned :class:`FrameSummary`
 
279
      objects will not have read their lines in yet, making the cost of
 
280
      creating the :class:`StackSummary` cheaper (which may be valuable if it
 
281
      may not actually get formatted). If *capture_locals* is ``True`` the
 
282
      local variables in each :class:`FrameSummary` are captured as object
 
283
      representations.
 
284
 
 
285
   .. classmethod:: from_list(a_list)
 
286
 
 
287
      Construct a :class:`StackSummary` object from a supplied old-style list
 
288
      of tuples. Each tuple should be a 4-tuple with filename, lineno, name,
 
289
      line as the elements.
 
290
 
 
291
 
 
292
:class:`FrameSummary` Objects
 
293
-----------------------------
 
294
 
 
295
.. versionadded:: 3.5
 
296
 
 
297
:class:`FrameSummary` objects represent a single frame in a traceback.
 
298
 
 
299
.. class:: FrameSummary(filename, lineno, name, lookup_line=True, locals=None, line=None)
 
300
 
 
301
   Represent a single frame in the traceback or stack that is being formatted
 
302
   or printed. It may optionally have a stringified version of the frames
 
303
   locals included in it. If *lookup_line* is ``False``, the source code is not
 
304
   looked up until the :class:`FrameSummary` has the :attr:`~FrameSummary.line`
 
305
   attribute accessed (which also happens when casting it to a tuple).
 
306
   :attr:`~FrameSummary.line` may be directly provided, and will prevent line
 
307
   lookups happening at all. *locals* is an optional local variable
 
308
   dictionary, and if supplied the variable representations are stored in the
 
309
   summary for later display.
 
310
 
 
311
.. _traceback-example:
 
312
 
 
313
Traceback Examples
 
314
------------------
 
315
 
 
316
This simple example implements a basic read-eval-print loop, similar to (but
 
317
less useful than) the standard Python interactive interpreter loop.  For a more
 
318
complete implementation of the interpreter loop, refer to the :mod:`code`
 
319
module. ::
 
320
 
 
321
   import sys, traceback
 
322
 
 
323
   def run_user_code(envdir):
 
324
       source = input(">>> ")
 
325
       try:
 
326
           exec(source, envdir)
 
327
       except Exception:
 
328
           print("Exception in user code:")
 
329
           print("-"*60)
 
330
           traceback.print_exc(file=sys.stdout)
 
331
           print("-"*60)
 
332
 
 
333
   envdir = {}
 
334
   while True:
 
335
       run_user_code(envdir)
 
336
 
 
337
 
 
338
The following example demonstrates the different ways to print and format the
 
339
exception and traceback:
 
340
 
 
341
.. testcode::
 
342
 
 
343
   import sys, traceback
 
344
 
 
345
   def lumberjack():
 
346
       bright_side_of_death()
 
347
 
 
348
   def bright_side_of_death():
 
349
       return tuple()[0]
 
350
 
 
351
   try:
 
352
       lumberjack()
 
353
   except IndexError:
 
354
       exc_type, exc_value, exc_traceback = sys.exc_info()
 
355
       print("*** print_tb:")
 
356
       traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
 
357
       print("*** print_exception:")
 
358
       traceback.print_exception(exc_type, exc_value, exc_traceback,
 
359
                                 limit=2, file=sys.stdout)
 
360
       print("*** print_exc:")
 
361
       traceback.print_exc()
 
362
       print("*** format_exc, first and last line:")
 
363
       formatted_lines = traceback.format_exc().splitlines()
 
364
       print(formatted_lines[0])
 
365
       print(formatted_lines[-1])
 
366
       print("*** format_exception:")
 
367
       print(repr(traceback.format_exception(exc_type, exc_value,
 
368
                                             exc_traceback)))
 
369
       print("*** extract_tb:")
 
370
       print(repr(traceback.extract_tb(exc_traceback)))
 
371
       print("*** format_tb:")
 
372
       print(repr(traceback.format_tb(exc_traceback)))
 
373
       print("*** tb_lineno:", exc_traceback.tb_lineno)
 
374
 
 
375
The output for the example would look similar to this:
 
376
 
 
377
.. testoutput::
 
378
   :options: +NORMALIZE_WHITESPACE
 
379
 
 
380
   *** print_tb:
 
381
     File "<doctest...>", line 10, in <module>
 
382
       lumberjack()
 
383
   *** print_exception:
 
384
   Traceback (most recent call last):
 
385
     File "<doctest...>", line 10, in <module>
 
386
       lumberjack()
 
387
     File "<doctest...>", line 4, in lumberjack
 
388
       bright_side_of_death()
 
389
   IndexError: tuple index out of range
 
390
   *** print_exc:
 
391
   Traceback (most recent call last):
 
392
     File "<doctest...>", line 10, in <module>
 
393
       lumberjack()
 
394
     File "<doctest...>", line 4, in lumberjack
 
395
       bright_side_of_death()
 
396
   IndexError: tuple index out of range
 
397
   *** format_exc, first and last line:
 
398
   Traceback (most recent call last):
 
399
   IndexError: tuple index out of range
 
400
   *** format_exception:
 
401
   ['Traceback (most recent call last):\n',
 
402
    '  File "<doctest...>", line 10, in <module>\n    lumberjack()\n',
 
403
    '  File "<doctest...>", line 4, in lumberjack\n    bright_side_of_death()\n',
 
404
    '  File "<doctest...>", line 7, in bright_side_of_death\n    return tuple()[0]\n',
 
405
    'IndexError: tuple index out of range\n']
 
406
   *** extract_tb:
 
407
   [('<doctest...>', 10, '<module>', 'lumberjack()'),
 
408
    ('<doctest...>', 4, 'lumberjack', 'bright_side_of_death()'),
 
409
    ('<doctest...>', 7, 'bright_side_of_death', 'return tuple()[0]')]
 
410
   *** format_tb:
 
411
   ['  File "<doctest...>", line 10, in <module>\n    lumberjack()\n',
 
412
    '  File "<doctest...>", line 4, in lumberjack\n    bright_side_of_death()\n',
 
413
    '  File "<doctest...>", line 7, in bright_side_of_death\n    return tuple()[0]\n']
 
414
   *** tb_lineno: 10
 
415
 
 
416
 
 
417
The following example shows the different ways to print and format the stack::
 
418
 
 
419
   >>> import traceback
 
420
   >>> def another_function():
 
421
   ...     lumberstack()
 
422
   ...
 
423
   >>> def lumberstack():
 
424
   ...     traceback.print_stack()
 
425
   ...     print(repr(traceback.extract_stack()))
 
426
   ...     print(repr(traceback.format_stack()))
 
427
   ...
 
428
   >>> another_function()
 
429
     File "<doctest>", line 10, in <module>
 
430
       another_function()
 
431
     File "<doctest>", line 3, in another_function
 
432
       lumberstack()
 
433
     File "<doctest>", line 6, in lumberstack
 
434
       traceback.print_stack()
 
435
   [('<doctest>', 10, '<module>', 'another_function()'),
 
436
    ('<doctest>', 3, 'another_function', 'lumberstack()'),
 
437
    ('<doctest>', 7, 'lumberstack', 'print(repr(traceback.extract_stack()))')]
 
438
   ['  File "<doctest>", line 10, in <module>\n    another_function()\n',
 
439
    '  File "<doctest>", line 3, in another_function\n    lumberstack()\n',
 
440
    '  File "<doctest>", line 8, in lumberstack\n    print(repr(traceback.format_stack()))\n']
 
441
 
 
442
 
 
443
This last example demonstrates the final few formatting functions:
 
444
 
 
445
.. doctest::
 
446
   :options: +NORMALIZE_WHITESPACE
 
447
 
 
448
   >>> import traceback
 
449
   >>> traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'),
 
450
   ...                        ('eggs.py', 42, 'eggs', 'return "bacon"')])
 
451
   ['  File "spam.py", line 3, in <module>\n    spam.eggs()\n',
 
452
    '  File "eggs.py", line 42, in eggs\n    return "bacon"\n']
 
453
   >>> an_error = IndexError('tuple index out of range')
 
454
   >>> traceback.format_exception_only(type(an_error), an_error)
 
455
   ['IndexError: tuple index out of range\n']