/Doc/library/traceback.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 278 lines · 206 code · 72 blank · 0 comment · 0 complexity · 528848f531dc022da80b5bfd85c803a1 MD5 · raw file

  1. :mod:`traceback` --- Print or retrieve a stack traceback
  2. ========================================================
  3. .. module:: traceback
  4. :synopsis: Print or retrieve a stack traceback.
  5. This module provides a standard interface to extract, format and print stack
  6. traces of Python programs. It exactly mimics the behavior of the Python
  7. interpreter when it prints a stack trace. This is useful when you want to print
  8. stack traces under program control, such as in a "wrapper" around the
  9. interpreter.
  10. .. index:: object: traceback
  11. The module uses traceback objects --- this is the object type that is stored in
  12. the variables :data:`sys.exc_traceback` (deprecated) and :data:`sys.last_traceback` and
  13. returned as the third item from :func:`sys.exc_info`.
  14. The module defines the following functions:
  15. .. function:: print_tb(traceback[, limit[, file]])
  16. Print up to *limit* stack trace entries from *traceback*. If *limit* is omitted
  17. or ``None``, all entries are printed. If *file* is omitted or ``None``, the
  18. output goes to ``sys.stderr``; otherwise it should be an open file or file-like
  19. object to receive the output.
  20. .. function:: print_exception(type, value, traceback[, limit[, file]])
  21. Print exception information and up to *limit* stack trace entries from
  22. *traceback* to *file*. This differs from :func:`print_tb` in the following ways:
  23. (1) if *traceback* is not ``None``, it prints a header ``Traceback (most recent
  24. call last):``; (2) it prints the exception *type* and *value* after the stack
  25. trace; (3) if *type* is :exc:`SyntaxError` and *value* has the appropriate
  26. format, it prints the line where the syntax error occurred with a caret
  27. indicating the approximate position of the error.
  28. .. function:: print_exc([limit[, file]])
  29. This is a shorthand for ``print_exception(sys.exc_type, sys.exc_value,
  30. sys.exc_traceback, limit, file)``. (In fact, it uses :func:`sys.exc_info` to
  31. retrieve the same information in a thread-safe way instead of using the
  32. deprecated variables.)
  33. .. function:: format_exc([limit])
  34. This is like ``print_exc(limit)`` but returns a string instead of printing to a
  35. file.
  36. .. versionadded:: 2.4
  37. .. function:: print_last([limit[, file]])
  38. This is a shorthand for ``print_exception(sys.last_type, sys.last_value,
  39. sys.last_traceback, limit, file)``. In general it will work only after
  40. an exception has reached an interactive prompt (see :data:`sys.last_type`).
  41. .. function:: print_stack([f[, limit[, file]]])
  42. This function prints a stack trace from its invocation point. The optional *f*
  43. argument can be used to specify an alternate stack frame to start. The optional
  44. *limit* and *file* arguments have the same meaning as for
  45. :func:`print_exception`.
  46. .. function:: extract_tb(traceback[, limit])
  47. Return a list of up to *limit* "pre-processed" stack trace entries extracted
  48. from the traceback object *traceback*. It is useful for alternate formatting of
  49. stack traces. If *limit* is omitted or ``None``, all entries are extracted. A
  50. "pre-processed" stack trace entry is a quadruple (*filename*, *line number*,
  51. *function name*, *text*) representing the information that is usually printed
  52. for a stack trace. The *text* is a string with leading and trailing whitespace
  53. stripped; if the source is not available it is ``None``.
  54. .. function:: extract_stack([f[, limit]])
  55. Extract the raw traceback from the current stack frame. The return value has
  56. the same format as for :func:`extract_tb`. The optional *f* and *limit*
  57. arguments have the same meaning as for :func:`print_stack`.
  58. .. function:: format_list(list)
  59. Given a list of tuples as returned by :func:`extract_tb` or
  60. :func:`extract_stack`, return a list of strings ready for printing. Each string
  61. in the resulting list corresponds to the item with the same index in the
  62. argument list. Each string ends in a newline; the strings may contain internal
  63. newlines as well, for those items whose source text line is not ``None``.
  64. .. function:: format_exception_only(type, value)
  65. Format the exception part of a traceback. The arguments are the exception type
  66. and value such as given by ``sys.last_type`` and ``sys.last_value``. The return
  67. value is a list of strings, each ending in a newline. Normally, the list
  68. contains a single string; however, for :exc:`SyntaxError` exceptions, it
  69. contains several lines that (when printed) display detailed information about
  70. where the syntax error occurred. The message indicating which exception
  71. occurred is the always last string in the list.
  72. .. function:: format_exception(type, value, tb[, limit])
  73. Format a stack trace and the exception information. The arguments have the
  74. same meaning as the corresponding arguments to :func:`print_exception`. The
  75. return value is a list of strings, each ending in a newline and some containing
  76. internal newlines. When these lines are concatenated and printed, exactly the
  77. same text is printed as does :func:`print_exception`.
  78. .. function:: format_tb(tb[, limit])
  79. A shorthand for ``format_list(extract_tb(tb, limit))``.
  80. .. function:: format_stack([f[, limit]])
  81. A shorthand for ``format_list(extract_stack(f, limit))``.
  82. .. function:: tb_lineno(tb)
  83. This function returns the current line number set in the traceback object. This
  84. function was necessary because in versions of Python prior to 2.3 when the
  85. :option:`-O` flag was passed to Python the ``tb.tb_lineno`` was not updated
  86. correctly. This function has no use in versions past 2.3.
  87. .. _traceback-example:
  88. Traceback Examples
  89. ------------------
  90. This simple example implements a basic read-eval-print loop, similar to (but
  91. less useful than) the standard Python interactive interpreter loop. For a more
  92. complete implementation of the interpreter loop, refer to the :mod:`code`
  93. module. ::
  94. import sys, traceback
  95. def run_user_code(envdir):
  96. source = raw_input(">>> ")
  97. try:
  98. exec source in envdir
  99. except:
  100. print "Exception in user code:"
  101. print '-'*60
  102. traceback.print_exc(file=sys.stdout)
  103. print '-'*60
  104. envdir = {}
  105. while 1:
  106. run_user_code(envdir)
  107. The following example demonstrates the different ways to print and format the
  108. exception and traceback::
  109. import sys, traceback
  110. def lumberjack():
  111. bright_side_of_death()
  112. def bright_side_of_death():
  113. return tuple()[0]
  114. try:
  115. lumberjack()
  116. except:
  117. exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
  118. print "*** print_tb:"
  119. traceback.print_tb(exceptionTraceback, limit=1, file=sys.stdout)
  120. print "*** print_exception:"
  121. traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
  122. limit=2, file=sys.stdout)
  123. print "*** print_exc:"
  124. traceback.print_exc()
  125. print "*** format_exc, first and last line:"
  126. formatted_lines = traceback.format_exc().splitlines()
  127. print formatted_lines[0]
  128. print formatted_lines[-1]
  129. print "*** format_exception:"
  130. print repr(traceback.format_exception(exceptionType, exceptionValue,
  131. exceptionTraceback))
  132. print "*** extract_tb:"
  133. print repr(traceback.extract_tb(exceptionTraceback))
  134. print "*** format_tb:"
  135. print repr(traceback.format_tb(exceptionTraceback))
  136. print "*** tb_lineno:", traceback.tb_lineno(exceptionTraceback)
  137. The output for the example would look similar to this::
  138. *** print_tb:
  139. File "<doctest...>", line 10, in <module>
  140. lumberjack()
  141. *** print_exception:
  142. Traceback (most recent call last):
  143. File "<doctest...>", line 10, in <module>
  144. lumberjack()
  145. File "<doctest...>", line 4, in lumberjack
  146. bright_side_of_death()
  147. IndexError: tuple index out of range
  148. *** print_exc:
  149. Traceback (most recent call last):
  150. File "<doctest...>", line 10, in <module>
  151. lumberjack()
  152. File "<doctest...>", line 4, in lumberjack
  153. bright_side_of_death()
  154. IndexError: tuple index out of range
  155. *** format_exc, first and last line:
  156. Traceback (most recent call last):
  157. IndexError: tuple index out of range
  158. *** format_exception:
  159. ['Traceback (most recent call last):\n',
  160. ' File "<doctest...>", line 10, in <module>\n lumberjack()\n',
  161. ' File "<doctest...>", line 4, in lumberjack\n bright_side_of_death()\n',
  162. ' File "<doctest...>", line 7, in bright_side_of_death\n return tuple()[0]\n',
  163. 'IndexError: tuple index out of range\n']
  164. *** extract_tb:
  165. [('<doctest...>', 10, '<module>', 'lumberjack()'),
  166. ('<doctest...>', 4, 'lumberjack', 'bright_side_of_death()'),
  167. ('<doctest...>', 7, 'bright_side_of_death', 'return tuple()[0]')]
  168. *** format_tb:
  169. [' File "<doctest...>", line 10, in <module>\n lumberjack()\n',
  170. ' File "<doctest...>", line 4, in lumberjack\n bright_side_of_death()\n',
  171. ' File "<doctest...>", line 7, in bright_side_of_death\n return tuple()[0]\n']
  172. *** tb_lineno: 10
  173. The following example shows the different ways to print and format the stack::
  174. >>> import traceback
  175. >>> def another_function():
  176. ... lumberstack()
  177. ...
  178. >>> def lumberstack():
  179. ... traceback.print_stack()
  180. ... print repr(traceback.extract_stack())
  181. ... print repr(traceback.format_stack())
  182. ...
  183. >>> another_function()
  184. File "<doctest>", line 10, in <module>
  185. another_function()
  186. File "<doctest>", line 3, in another_function
  187. lumberstack()
  188. File "<doctest>", line 6, in lumberstack
  189. traceback.print_stack()
  190. [('<doctest>', 10, '<module>', 'another_function()'),
  191. ('<doctest>', 3, 'another_function', 'lumberstack()'),
  192. ('<doctest>', 7, 'lumberstack', 'print repr(traceback.extract_stack())')]
  193. [' File "<doctest>", line 10, in <module>\n another_function()\n',
  194. ' File "<doctest>", line 3, in another_function\n lumberstack()\n',
  195. ' File "<doctest>", line 8, in lumberstack\n print repr(traceback.format_stack())\n']
  196. This last example demonstrates the final few formatting functions:
  197. .. doctest::
  198. :options: +NORMALIZE_WHITESPACE
  199. >>> import traceback
  200. >>> traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'),
  201. ... ('eggs.py', 42, 'eggs', 'return "bacon"')])
  202. [' File "spam.py", line 3, in <module>\n spam.eggs()\n',
  203. ' File "eggs.py", line 42, in eggs\n return "bacon"\n']
  204. >>> an_error = IndexError('tuple index out of range')
  205. >>> traceback.format_exception_only(type(an_error), an_error)
  206. ['IndexError: tuple index out of range\n']