/Lib/traceback.py

http://unladen-swallow.googlecode.com/ · Python · 312 lines · 289 code · 9 blank · 14 comment · 10 complexity · 1bc14f82182c8b25614c2822bbaf7fd7 MD5 · raw file

  1. """Extract, format and print information about Python stack traces."""
  2. import linecache
  3. import sys
  4. import types
  5. __all__ = ['extract_stack', 'extract_tb', 'format_exception',
  6. 'format_exception_only', 'format_list', 'format_stack',
  7. 'format_tb', 'print_exc', 'format_exc', 'print_exception',
  8. 'print_last', 'print_stack', 'print_tb', 'tb_lineno']
  9. def _print(file, str='', terminator='\n'):
  10. file.write(str+terminator)
  11. def print_list(extracted_list, file=None):
  12. """Print the list of tuples as returned by extract_tb() or
  13. extract_stack() as a formatted stack trace to the given file."""
  14. if file is None:
  15. file = sys.stderr
  16. for filename, lineno, name, line in extracted_list:
  17. _print(file,
  18. ' File "%s", line %d, in %s' % (filename,lineno,name))
  19. if line:
  20. _print(file, ' %s' % line.strip())
  21. def format_list(extracted_list):
  22. """Format a list of traceback entry tuples for printing.
  23. Given a list of tuples as returned by extract_tb() or
  24. extract_stack(), return a list of strings ready for printing.
  25. Each string in the resulting list corresponds to the item with the
  26. same index in the argument list. Each string ends in a newline;
  27. the strings may contain internal newlines as well, for those items
  28. whose source text line is not None.
  29. """
  30. list = []
  31. for filename, lineno, name, line in extracted_list:
  32. item = ' File "%s", line %d, in %s\n' % (filename,lineno,name)
  33. if line:
  34. item = item + ' %s\n' % line.strip()
  35. list.append(item)
  36. return list
  37. def print_tb(tb, limit=None, file=None):
  38. """Print up to 'limit' stack trace entries from the traceback 'tb'.
  39. If 'limit' is omitted or None, all entries are printed. If 'file'
  40. is omitted or None, the output goes to sys.stderr; otherwise
  41. 'file' should be an open file or file-like object with a write()
  42. method.
  43. """
  44. if file is None:
  45. file = sys.stderr
  46. if limit is None:
  47. if hasattr(sys, 'tracebacklimit'):
  48. limit = sys.tracebacklimit
  49. n = 0
  50. while tb is not None and (limit is None or n < limit):
  51. f = tb.tb_frame
  52. lineno = tb.tb_lineno
  53. co = f.f_code
  54. filename = co.co_filename
  55. name = co.co_name
  56. _print(file,
  57. ' File "%s", line %d, in %s' % (filename,lineno,name))
  58. linecache.checkcache(filename)
  59. line = linecache.getline(filename, lineno, f.f_globals)
  60. if line: _print(file, ' ' + line.strip())
  61. tb = tb.tb_next
  62. n = n+1
  63. def format_tb(tb, limit = None):
  64. """A shorthand for 'format_list(extract_stack(f, limit))."""
  65. return format_list(extract_tb(tb, limit))
  66. def extract_tb(tb, limit = None):
  67. """Return list of up to limit pre-processed entries from traceback.
  68. This is useful for alternate formatting of stack traces. If
  69. 'limit' is omitted or None, all entries are extracted. A
  70. pre-processed stack trace entry is a quadruple (filename, line
  71. number, function name, text) representing the information that is
  72. usually printed for a stack trace. The text is a string with
  73. leading and trailing whitespace stripped; if the source is not
  74. available it is None.
  75. """
  76. if limit is None:
  77. if hasattr(sys, 'tracebacklimit'):
  78. limit = sys.tracebacklimit
  79. list = []
  80. n = 0
  81. while tb is not None and (limit is None or n < limit):
  82. f = tb.tb_frame
  83. lineno = tb.tb_lineno
  84. co = f.f_code
  85. filename = co.co_filename
  86. name = co.co_name
  87. linecache.checkcache(filename)
  88. line = linecache.getline(filename, lineno, f.f_globals)
  89. if line: line = line.strip()
  90. else: line = None
  91. list.append((filename, lineno, name, line))
  92. tb = tb.tb_next
  93. n = n+1
  94. return list
  95. def print_exception(etype, value, tb, limit=None, file=None):
  96. """Print exception up to 'limit' stack trace entries from 'tb' to 'file'.
  97. This differs from print_tb() in the following ways: (1) if
  98. traceback is not None, it prints a header "Traceback (most recent
  99. call last):"; (2) it prints the exception type and value after the
  100. stack trace; (3) if type is SyntaxError and value has the
  101. appropriate format, it prints the line where the syntax error
  102. occurred with a caret on the next line indicating the approximate
  103. position of the error.
  104. """
  105. if file is None:
  106. file = sys.stderr
  107. if tb:
  108. _print(file, 'Traceback (most recent call last):')
  109. print_tb(tb, limit, file)
  110. lines = format_exception_only(etype, value)
  111. for line in lines[:-1]:
  112. _print(file, line, ' ')
  113. _print(file, lines[-1], '')
  114. def format_exception(etype, value, tb, limit = None):
  115. """Format a stack trace and the exception information.
  116. The arguments have the same meaning as the corresponding arguments
  117. to print_exception(). The return value is a list of strings, each
  118. ending in a newline and some containing internal newlines. When
  119. these lines are concatenated and printed, exactly the same text is
  120. printed as does print_exception().
  121. """
  122. if tb:
  123. list = ['Traceback (most recent call last):\n']
  124. list = list + format_tb(tb, limit)
  125. else:
  126. list = []
  127. list = list + format_exception_only(etype, value)
  128. return list
  129. def format_exception_only(etype, value):
  130. """Format the exception part of a traceback.
  131. The arguments are the exception type and value such as given by
  132. sys.last_type and sys.last_value. The return value is a list of
  133. strings, each ending in a newline.
  134. Normally, the list contains a single string; however, for
  135. SyntaxError exceptions, it contains several lines that (when
  136. printed) display detailed information about where the syntax
  137. error occurred.
  138. The message indicating which exception occurred is always the last
  139. string in the list.
  140. """
  141. # An instance should not have a meaningful value parameter, but
  142. # sometimes does, particularly for string exceptions, such as
  143. # >>> raise string1, string2 # deprecated
  144. #
  145. # Clear these out first because issubtype(string1, SyntaxError)
  146. # would throw another exception and mask the original problem.
  147. if (isinstance(etype, BaseException) or
  148. isinstance(etype, types.InstanceType) or
  149. etype is None or type(etype) is str):
  150. return [_format_final_exc_line(etype, value)]
  151. stype = etype.__name__
  152. if not issubclass(etype, SyntaxError):
  153. return [_format_final_exc_line(stype, value)]
  154. # It was a syntax error; show exactly where the problem was found.
  155. lines = []
  156. try:
  157. msg, (filename, lineno, offset, badline) = value.args
  158. except Exception:
  159. pass
  160. else:
  161. filename = filename or "<string>"
  162. lines.append(' File "%s", line %d\n' % (filename, lineno))
  163. if badline is not None:
  164. lines.append(' %s\n' % badline.strip())
  165. if offset is not None:
  166. caretspace = badline[:offset].lstrip()
  167. # non-space whitespace (likes tabs) must be kept for alignment
  168. caretspace = ((c.isspace() and c or ' ') for c in caretspace)
  169. # only three spaces to account for offset1 == pos 0
  170. lines.append(' %s^\n' % ''.join(caretspace))
  171. value = msg
  172. lines.append(_format_final_exc_line(stype, value))
  173. return lines
  174. def _format_final_exc_line(etype, value):
  175. """Return a list of a single line -- normal case for format_exception_only"""
  176. valuestr = _some_str(value)
  177. if value is None or not valuestr:
  178. line = "%s\n" % etype
  179. else:
  180. line = "%s: %s\n" % (etype, valuestr)
  181. return line
  182. def _some_str(value):
  183. try:
  184. return str(value)
  185. except:
  186. return '<unprintable %s object>' % type(value).__name__
  187. def print_exc(limit=None, file=None):
  188. """Shorthand for 'print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)'.
  189. (In fact, it uses sys.exc_info() to retrieve the same information
  190. in a thread-safe way.)"""
  191. if file is None:
  192. file = sys.stderr
  193. try:
  194. etype, value, tb = sys.exc_info()
  195. print_exception(etype, value, tb, limit, file)
  196. finally:
  197. etype = value = tb = None
  198. def format_exc(limit=None):
  199. """Like print_exc() but return a string."""
  200. try:
  201. etype, value, tb = sys.exc_info()
  202. return ''.join(format_exception(etype, value, tb, limit))
  203. finally:
  204. etype = value = tb = None
  205. def print_last(limit=None, file=None):
  206. """This is a shorthand for 'print_exception(sys.last_type,
  207. sys.last_value, sys.last_traceback, limit, file)'."""
  208. if file is None:
  209. file = sys.stderr
  210. print_exception(sys.last_type, sys.last_value, sys.last_traceback,
  211. limit, file)
  212. def print_stack(f=None, limit=None, file=None):
  213. """Print a stack trace from its invocation point.
  214. The optional 'f' argument can be used to specify an alternate
  215. stack frame at which to start. The optional 'limit' and 'file'
  216. arguments have the same meaning as for print_exception().
  217. """
  218. if f is None:
  219. try:
  220. raise ZeroDivisionError
  221. except ZeroDivisionError:
  222. f = sys.exc_info()[2].tb_frame.f_back
  223. print_list(extract_stack(f, limit), file)
  224. def format_stack(f=None, limit=None):
  225. """Shorthand for 'format_list(extract_stack(f, limit))'."""
  226. if f is None:
  227. try:
  228. raise ZeroDivisionError
  229. except ZeroDivisionError:
  230. f = sys.exc_info()[2].tb_frame.f_back
  231. return format_list(extract_stack(f, limit))
  232. def extract_stack(f=None, limit = None):
  233. """Extract the raw traceback from the current stack frame.
  234. The return value has the same format as for extract_tb(). The
  235. optional 'f' and 'limit' arguments have the same meaning as for
  236. print_stack(). Each item in the list is a quadruple (filename,
  237. line number, function name, text), and the entries are in order
  238. from oldest to newest stack frame.
  239. """
  240. if f is None:
  241. try:
  242. raise ZeroDivisionError
  243. except ZeroDivisionError:
  244. f = sys.exc_info()[2].tb_frame.f_back
  245. if limit is None:
  246. if hasattr(sys, 'tracebacklimit'):
  247. limit = sys.tracebacklimit
  248. list = []
  249. n = 0
  250. while f is not None and (limit is None or n < limit):
  251. lineno = f.f_lineno
  252. co = f.f_code
  253. filename = co.co_filename
  254. name = co.co_name
  255. linecache.checkcache(filename)
  256. line = linecache.getline(filename, lineno, f.f_globals)
  257. if line: line = line.strip()
  258. else: line = None
  259. list.append((filename, lineno, name, line))
  260. f = f.f_back
  261. n = n+1
  262. list.reverse()
  263. return list
  264. def tb_lineno(tb):
  265. """Calculate correct line number of traceback given in tb.
  266. Obsolete in 2.3.
  267. """
  268. return tb.tb_lineno