PageRenderTime 52ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/edk2/AppPkg/Applications/Python/Python-2.7.2/Lib/traceback.py

https://gitlab.com/envieidoc/Clover
Python | 319 lines | 315 code | 3 blank | 1 comment | 0 complexity | 95dbdcaf765f90eacd5a1beef31c2ae4 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:
  112. _print(file, line, '')
  113. def format_exception(etype, value, tb, limit = None):
  114. """Format a stack trace and the exception information.
  115. The arguments have the same meaning as the corresponding arguments
  116. to print_exception(). The return value is a list of strings, each
  117. ending in a newline and some containing internal newlines. When
  118. these lines are concatenated and printed, exactly the same text is
  119. printed as does print_exception().
  120. """
  121. if tb:
  122. list = ['Traceback (most recent call last):\n']
  123. list = list + format_tb(tb, limit)
  124. else:
  125. list = []
  126. list = list + format_exception_only(etype, value)
  127. return list
  128. def format_exception_only(etype, value):
  129. """Format the exception part of a traceback.
  130. The arguments are the exception type and value such as given by
  131. sys.last_type and sys.last_value. The return value is a list of
  132. strings, each ending in a newline.
  133. Normally, the list contains a single string; however, for
  134. SyntaxError exceptions, it contains several lines that (when
  135. printed) display detailed information about where the syntax
  136. error occurred.
  137. The message indicating which exception occurred is always the last
  138. string in the list.
  139. """
  140. # An instance should not have a meaningful value parameter, but
  141. # sometimes does, particularly for string exceptions, such as
  142. # >>> raise string1, string2 # deprecated
  143. #
  144. # Clear these out first because issubtype(string1, SyntaxError)
  145. # would throw another exception and mask the original problem.
  146. if (isinstance(etype, BaseException) or
  147. isinstance(etype, types.InstanceType) or
  148. etype is None or type(etype) is str):
  149. return [_format_final_exc_line(etype, value)]
  150. stype = etype.__name__
  151. if not issubclass(etype, SyntaxError):
  152. return [_format_final_exc_line(stype, value)]
  153. # It was a syntax error; show exactly where the problem was found.
  154. lines = []
  155. try:
  156. msg, (filename, lineno, offset, badline) = value.args
  157. except Exception:
  158. pass
  159. else:
  160. filename = filename or "<string>"
  161. lines.append(' File "%s", line %d\n' % (filename, lineno))
  162. if badline is not None:
  163. lines.append(' %s\n' % badline.strip())
  164. if offset is not None:
  165. caretspace = badline.rstrip('\n')[:offset].lstrip()
  166. # non-space whitespace (likes tabs) must be kept for alignment
  167. caretspace = ((c.isspace() and c or ' ') for c in caretspace)
  168. # only three spaces to account for offset1 == pos 0
  169. lines.append(' %s^\n' % ''.join(caretspace))
  170. value = msg
  171. lines.append(_format_final_exc_line(stype, value))
  172. return lines
  173. def _format_final_exc_line(etype, value):
  174. """Return a list of a single line -- normal case for format_exception_only"""
  175. valuestr = _some_str(value)
  176. if value is None or not valuestr:
  177. line = "%s\n" % etype
  178. else:
  179. line = "%s: %s\n" % (etype, valuestr)
  180. return line
  181. def _some_str(value):
  182. try:
  183. return str(value)
  184. except Exception:
  185. pass
  186. try:
  187. value = unicode(value)
  188. return value.encode("ascii", "backslashreplace")
  189. except Exception:
  190. pass
  191. return '<unprintable %s object>' % type(value).__name__
  192. def print_exc(limit=None, file=None):
  193. """Shorthand for 'print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)'.
  194. (In fact, it uses sys.exc_info() to retrieve the same information
  195. in a thread-safe way.)"""
  196. if file is None:
  197. file = sys.stderr
  198. try:
  199. etype, value, tb = sys.exc_info()
  200. print_exception(etype, value, tb, limit, file)
  201. finally:
  202. etype = value = tb = None
  203. def format_exc(limit=None):
  204. """Like print_exc() but return a string."""
  205. try:
  206. etype, value, tb = sys.exc_info()
  207. return ''.join(format_exception(etype, value, tb, limit))
  208. finally:
  209. etype = value = tb = None
  210. def print_last(limit=None, file=None):
  211. """This is a shorthand for 'print_exception(sys.last_type,
  212. sys.last_value, sys.last_traceback, limit, file)'."""
  213. if not hasattr(sys, "last_type"):
  214. raise ValueError("no last exception")
  215. if file is None:
  216. file = sys.stderr
  217. print_exception(sys.last_type, sys.last_value, sys.last_traceback,
  218. limit, file)
  219. def print_stack(f=None, limit=None, file=None):
  220. """Print a stack trace from its invocation point.
  221. The optional 'f' argument can be used to specify an alternate
  222. stack frame at which to start. The optional 'limit' and 'file'
  223. arguments have the same meaning as for print_exception().
  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. print_list(extract_stack(f, limit), file)
  231. def format_stack(f=None, limit=None):
  232. """Shorthand for 'format_list(extract_stack(f, limit))'."""
  233. if f is None:
  234. try:
  235. raise ZeroDivisionError
  236. except ZeroDivisionError:
  237. f = sys.exc_info()[2].tb_frame.f_back
  238. return format_list(extract_stack(f, limit))
  239. def extract_stack(f=None, limit = None):
  240. """Extract the raw traceback from the current stack frame.
  241. The return value has the same format as for extract_tb(). The
  242. optional 'f' and 'limit' arguments have the same meaning as for
  243. print_stack(). Each item in the list is a quadruple (filename,
  244. line number, function name, text), and the entries are in order
  245. from oldest to newest stack frame.
  246. """
  247. if f is None:
  248. try:
  249. raise ZeroDivisionError
  250. except ZeroDivisionError:
  251. f = sys.exc_info()[2].tb_frame.f_back
  252. if limit is None:
  253. if hasattr(sys, 'tracebacklimit'):
  254. limit = sys.tracebacklimit
  255. list = []
  256. n = 0
  257. while f is not None and (limit is None or n < limit):
  258. lineno = f.f_lineno
  259. co = f.f_code
  260. filename = co.co_filename
  261. name = co.co_name
  262. linecache.checkcache(filename)
  263. line = linecache.getline(filename, lineno, f.f_globals)
  264. if line: line = line.strip()
  265. else: line = None
  266. list.append((filename, lineno, name, line))
  267. f = f.f_back
  268. n = n+1
  269. list.reverse()
  270. return list
  271. def tb_lineno(tb):
  272. """Calculate correct line number of traceback given in tb.
  273. Obsolete in 2.3.
  274. """
  275. return tb.tb_lineno