You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

traceback.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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', 'print_exception', 'print_last',
  8. '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 not file:
  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 not file:
  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_lineno(tb)
  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. line = linecache.getline(filename, lineno)
  59. if line: _print(file, ' ' + line.strip())
  60. tb = tb.tb_next
  61. n = n+1
  62. def format_tb(tb, limit = None):
  63. """A shorthand for 'format_list(extract_stack(f, limit))."""
  64. return format_list(extract_tb(tb, limit))
  65. def extract_tb(tb, limit = None):
  66. """Return list of up to limit pre-processed entries from traceback.
  67. This is useful for alternate formatting of stack traces. If
  68. 'limit' is omitted or None, all entries are extracted. A
  69. pre-processed stack trace entry is a quadruple (filename, line
  70. number, function name, text) representing the information that is
  71. usually printed for a stack trace. The text is a string with
  72. leading and trailing whitespace stripped; if the source is not
  73. available it is None.
  74. """
  75. if limit is None:
  76. if hasattr(sys, 'tracebacklimit'):
  77. limit = sys.tracebacklimit
  78. list = []
  79. n = 0
  80. while tb is not None and (limit is None or n < limit):
  81. f = tb.tb_frame
  82. lineno = tb_lineno(tb)
  83. co = f.f_code
  84. filename = co.co_filename
  85. name = co.co_name
  86. line = linecache.getline(filename, lineno)
  87. if line: line = line.strip()
  88. else: line = None
  89. list.append((filename, lineno, name, line))
  90. tb = tb.tb_next
  91. n = n+1
  92. return list
  93. def print_exception(etype, value, tb, limit=None, file=None):
  94. """Print exception up to 'limit' stack trace entries from 'tb' to 'file'.
  95. This differs from print_tb() in the following ways: (1) if
  96. traceback is not None, it prints a header "Traceback (most recent
  97. call last):"; (2) it prints the exception type and value after the
  98. stack trace; (3) if type is SyntaxError and value has the
  99. appropriate format, it prints the line where the syntax error
  100. occurred with a caret on the next line indicating the approximate
  101. position of the error.
  102. """
  103. if not file:
  104. file = sys.stderr
  105. if tb:
  106. _print(file, 'Traceback (most recent call last):')
  107. print_tb(tb, limit, file)
  108. lines = format_exception_only(etype, value)
  109. for line in lines[:-1]:
  110. _print(file, line, ' ')
  111. _print(file, lines[-1], '')
  112. def format_exception(etype, value, tb, limit = None):
  113. """Format a stack trace and the exception information.
  114. The arguments have the same meaning as the corresponding arguments
  115. to print_exception(). The return value is a list of strings, each
  116. ending in a newline and some containing internal newlines. When
  117. these lines are concatenated and printed, exactly the same text is
  118. printed as does print_exception().
  119. """
  120. if tb:
  121. list = ['Traceback (most recent call last):\n']
  122. list = list + format_tb(tb, limit)
  123. else:
  124. list = []
  125. list = list + format_exception_only(etype, value)
  126. return list
  127. def format_exception_only(etype, value):
  128. """Format the exception part of a traceback.
  129. The arguments are the exception type and value such as given by
  130. sys.last_type and sys.last_value. The return value is a list of
  131. strings, each ending in a newline. Normally, the list contains a
  132. single string; however, for SyntaxError exceptions, it contains
  133. several lines that (when printed) display detailed information
  134. about where the syntax error occurred. The message indicating
  135. which exception occurred is the always last string in the list.
  136. """
  137. list = []
  138. if type(etype) == types.ClassType:
  139. stype = etype.__name__
  140. else:
  141. stype = etype
  142. if value is None:
  143. list.append(str(stype) + '\n')
  144. else:
  145. if etype is SyntaxError:
  146. try:
  147. msg, (filename, lineno, offset, line) = value
  148. except:
  149. pass
  150. else:
  151. if not filename: filename = "<string>"
  152. list.append(' File "%s", line %d\n' %
  153. (filename, lineno))
  154. if line is not None:
  155. i = 0
  156. while i < len(line) and line[i].isspace():
  157. i = i+1
  158. list.append(' %s\n' % line.strip())
  159. if offset is not None:
  160. s = ' '
  161. for c in line[i:offset-1]:
  162. if c.isspace():
  163. s = s + c
  164. else:
  165. s = s + ' '
  166. list.append('%s^\n' % s)
  167. value = msg
  168. s = _some_str(value)
  169. if s:
  170. list.append('%s: %s\n' % (str(stype), s))
  171. else:
  172. list.append('%s\n' % str(stype))
  173. return list
  174. def _some_str(value):
  175. try:
  176. return str(value)
  177. except:
  178. return '<unprintable %s object>' % type(value).__name__
  179. def print_exc(limit=None, file=None):
  180. """Shorthand for 'print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)'.
  181. (In fact, it uses sys.exc_info() to retrieve the same information
  182. in a thread-safe way.)"""
  183. if not file:
  184. file = sys.stderr
  185. try:
  186. etype, value, tb = sys.exc_info()
  187. print_exception(etype, value, tb, limit, file)
  188. finally:
  189. etype = value = tb = None
  190. def print_last(limit=None, file=None):
  191. """This is a shorthand for 'print_exception(sys.last_type,
  192. sys.last_value, sys.last_traceback, limit, file)'."""
  193. if not file:
  194. file = sys.stderr
  195. print_exception(sys.last_type, sys.last_value, sys.last_traceback,
  196. limit, file)
  197. def print_stack(f=None, limit=None, file=None):
  198. """Print a stack trace from its invocation point.
  199. The optional 'f' argument can be used to specify an alternate
  200. stack frame at which to start. The optional 'limit' and 'file'
  201. arguments have the same meaning as for print_exception().
  202. """
  203. if f is None:
  204. try:
  205. raise ZeroDivisionError
  206. except ZeroDivisionError:
  207. f = sys.exc_info()[2].tb_frame.f_back
  208. print_list(extract_stack(f, limit), file)
  209. def format_stack(f=None, limit=None):
  210. """Shorthand for 'format_list(extract_stack(f, limit))'."""
  211. if f is None:
  212. try:
  213. raise ZeroDivisionError
  214. except ZeroDivisionError:
  215. f = sys.exc_info()[2].tb_frame.f_back
  216. return format_list(extract_stack(f, limit))
  217. def extract_stack(f=None, limit = None):
  218. """Extract the raw traceback from the current stack frame.
  219. The return value has the same format as for extract_tb(). The
  220. optional 'f' and 'limit' arguments have the same meaning as for
  221. print_stack(). Each item in the list is a quadruple (filename,
  222. line number, function name, text), and the entries are in order
  223. from oldest to newest stack frame.
  224. """
  225. if f is None:
  226. try:
  227. raise ZeroDivisionError
  228. except ZeroDivisionError:
  229. f = sys.exc_info()[2].tb_frame.f_back
  230. if limit is None:
  231. if hasattr(sys, 'tracebacklimit'):
  232. limit = sys.tracebacklimit
  233. list = []
  234. n = 0
  235. while f is not None and (limit is None or n < limit):
  236. lineno = f.f_lineno # XXX Too bad if -O is used
  237. co = f.f_code
  238. filename = co.co_filename
  239. name = co.co_name
  240. line = linecache.getline(filename, lineno)
  241. if line: line = line.strip()
  242. else: line = None
  243. list.append((filename, lineno, name, line))
  244. f = f.f_back
  245. n = n+1
  246. list.reverse()
  247. return list
  248. def tb_lineno(tb):
  249. """Calculate correct line number of traceback given in tb.
  250. Even works with -O on.
  251. """
  252. # Coded by Marc-Andre Lemburg from the example of PyCode_Addr2Line()
  253. # in compile.c.
  254. # Revised version by Jim Hugunin to work with JPython too.
  255. c = tb.tb_frame.f_code
  256. if not hasattr(c, 'co_lnotab'):
  257. return tb.tb_lineno
  258. tab = c.co_lnotab
  259. line = c.co_firstlineno
  260. stopat = tb.tb_lasti
  261. addr = 0
  262. for i in range(0, len(tab), 2):
  263. addr = addr + ord(tab[i])
  264. if addr > stopat:
  265. break
  266. line = line + ord(tab[i+1])
  267. return line