traceback.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. """Extract, format and print information about Python stack traces."""
  2. import collections
  3. import itertools
  4. import linecache
  5. import sys
  6. __all__ = ['extract_stack', 'extract_tb', 'format_exception',
  7. 'format_exception_only', 'format_list', 'format_stack',
  8. 'format_tb', 'print_exc', 'format_exc', 'print_exception',
  9. 'print_last', 'print_stack', 'print_tb', 'clear_frames',
  10. 'FrameSummary', 'StackSummary', 'TracebackException',
  11. 'walk_stack', 'walk_tb']
  12. #
  13. # Formatting and printing lists of traceback lines.
  14. #
  15. def print_list(extracted_list, file=None):
  16. """Print the list of tuples as returned by extract_tb() or
  17. extract_stack() as a formatted stack trace to the given file."""
  18. if file is None:
  19. file = sys.stderr
  20. for item in StackSummary.from_list(extracted_list).format():
  21. print(item, file=file, end="")
  22. def format_list(extracted_list):
  23. """Format a list of traceback entry tuples for printing.
  24. Given a list of tuples as returned by extract_tb() or
  25. extract_stack(), return a list of strings ready for printing.
  26. Each string in the resulting list corresponds to the item with the
  27. same index in the argument list. Each string ends in a newline;
  28. the strings may contain internal newlines as well, for those items
  29. whose source text line is not None.
  30. """
  31. return StackSummary.from_list(extracted_list).format()
  32. #
  33. # Printing and Extracting Tracebacks.
  34. #
  35. def print_tb(tb, limit=None, file=None):
  36. """Print up to 'limit' stack trace entries from the traceback 'tb'.
  37. If 'limit' is omitted or None, all entries are printed. If 'file'
  38. is omitted or None, the output goes to sys.stderr; otherwise
  39. 'file' should be an open file or file-like object with a write()
  40. method.
  41. """
  42. print_list(extract_tb(tb, limit=limit), file=file)
  43. def format_tb(tb, limit=None):
  44. """A shorthand for 'format_list(extract_tb(tb, limit))'."""
  45. return extract_tb(tb, limit=limit).format()
  46. def extract_tb(tb, limit=None):
  47. """Return list of up to limit pre-processed entries from traceback.
  48. This is useful for alternate formatting of stack traces. If
  49. 'limit' is omitted or None, all entries are extracted. A
  50. pre-processed stack trace entry is a quadruple (filename, line
  51. number, function name, text) representing the information that is
  52. usually printed for a stack trace. The text is a string with
  53. leading and trailing whitespace stripped; if the source is not
  54. available it is None.
  55. """
  56. return StackSummary.extract(walk_tb(tb), limit=limit)
  57. #
  58. # Exception formatting and output.
  59. #
  60. _cause_message = (
  61. "\nThe above exception was the direct cause "
  62. "of the following exception:\n\n")
  63. _context_message = (
  64. "\nDuring handling of the above exception, "
  65. "another exception occurred:\n\n")
  66. def print_exception(etype, value, tb, limit=None, file=None, chain=True):
  67. """Print exception up to 'limit' stack trace entries from 'tb' to 'file'.
  68. This differs from print_tb() in the following ways: (1) if
  69. traceback is not None, it prints a header "Traceback (most recent
  70. call last):"; (2) it prints the exception type and value after the
  71. stack trace; (3) if type is SyntaxError and value has the
  72. appropriate format, it prints the line where the syntax error
  73. occurred with a caret on the next line indicating the approximate
  74. position of the error.
  75. """
  76. # format_exception has ignored etype for some time, and code such as cgitb
  77. # passes in bogus values as a result. For compatibility with such code we
  78. # ignore it here (rather than in the new TracebackException API).
  79. if file is None:
  80. file = sys.stderr
  81. for line in TracebackException(
  82. type(value), value, tb, limit=limit).format(chain=chain):
  83. print(line, file=file, end="")
  84. def format_exception(etype, value, tb, limit=None, chain=True):
  85. """Format a stack trace and the exception information.
  86. The arguments have the same meaning as the corresponding arguments
  87. to print_exception(). The return value is a list of strings, each
  88. ending in a newline and some containing internal newlines. When
  89. these lines are concatenated and printed, exactly the same text is
  90. printed as does print_exception().
  91. """
  92. # format_exception has ignored etype for some time, and code such as cgitb
  93. # passes in bogus values as a result. For compatibility with such code we
  94. # ignore it here (rather than in the new TracebackException API).
  95. return list(TracebackException(
  96. type(value), value, tb, limit=limit).format(chain=chain))
  97. def format_exception_only(etype, value):
  98. """Format the exception part of a traceback.
  99. The arguments are the exception type and value such as given by
  100. sys.last_type and sys.last_value. The return value is a list of
  101. strings, each ending in a newline.
  102. Normally, the list contains a single string; however, for
  103. SyntaxError exceptions, it contains several lines that (when
  104. printed) display detailed information about where the syntax
  105. error occurred.
  106. The message indicating which exception occurred is always the last
  107. string in the list.
  108. """
  109. return list(TracebackException(etype, value, None).format_exception_only())
  110. # -- not official API but folk probably use these two functions.
  111. def _format_final_exc_line(etype, value):
  112. valuestr = _some_str(value)
  113. if value == 'None' or value is None or not valuestr:
  114. line = "%s\n" % etype
  115. else:
  116. line = "%s: %s\n" % (etype, valuestr)
  117. return line
  118. def _some_str(value):
  119. try:
  120. return str(value)
  121. except:
  122. return '<unprintable %s object>' % type(value).__name__
  123. # --
  124. def print_exc(limit=None, file=None, chain=True):
  125. """Shorthand for 'print_exception(*sys.exc_info(), limit, file)'."""
  126. print_exception(*sys.exc_info(), limit=limit, file=file, chain=chain)
  127. def format_exc(limit=None, chain=True):
  128. """Like print_exc() but return a string."""
  129. return "".join(format_exception(*sys.exc_info(), limit=limit, chain=chain))
  130. def print_last(limit=None, file=None, chain=True):
  131. """This is a shorthand for 'print_exception(sys.last_type,
  132. sys.last_value, sys.last_traceback, limit, file)'."""
  133. if not hasattr(sys, "last_type"):
  134. raise ValueError("no last exception")
  135. print_exception(sys.last_type, sys.last_value, sys.last_traceback,
  136. limit, file, chain)
  137. #
  138. # Printing and Extracting Stacks.
  139. #
  140. def print_stack(f=None, limit=None, file=None):
  141. """Print a stack trace from its invocation point.
  142. The optional 'f' argument can be used to specify an alternate
  143. stack frame at which to start. The optional 'limit' and 'file'
  144. arguments have the same meaning as for print_exception().
  145. """
  146. if f is None:
  147. f = sys._getframe().f_back
  148. print_list(extract_stack(f, limit=limit), file=file)
  149. def format_stack(f=None, limit=None):
  150. """Shorthand for 'format_list(extract_stack(f, limit))'."""
  151. if f is None:
  152. f = sys._getframe().f_back
  153. return format_list(extract_stack(f, limit=limit))
  154. def extract_stack(f=None, limit=None):
  155. """Extract the raw traceback from the current stack frame.
  156. The return value has the same format as for extract_tb(). The
  157. optional 'f' and 'limit' arguments have the same meaning as for
  158. print_stack(). Each item in the list is a quadruple (filename,
  159. line number, function name, text), and the entries are in order
  160. from oldest to newest stack frame.
  161. """
  162. if f is None:
  163. f = sys._getframe().f_back
  164. stack = StackSummary.extract(walk_stack(f), limit=limit)
  165. stack.reverse()
  166. return stack
  167. def clear_frames(tb):
  168. "Clear all references to local variables in the frames of a traceback."
  169. while tb is not None:
  170. try:
  171. tb.tb_frame.clear()
  172. except RuntimeError:
  173. # Ignore the exception raised if the frame is still executing.
  174. pass
  175. tb = tb.tb_next
  176. class FrameSummary:
  177. """A single frame from a traceback.
  178. - :attr:`filename` The filename for the frame.
  179. - :attr:`lineno` The line within filename for the frame that was
  180. active when the frame was captured.
  181. - :attr:`name` The name of the function or method that was executing
  182. when the frame was captured.
  183. - :attr:`line` The text from the linecache module for the
  184. of code that was running when the frame was captured.
  185. - :attr:`locals` Either None if locals were not supplied, or a dict
  186. mapping the name to the repr() of the variable.
  187. """
  188. __slots__ = ('filename', 'lineno', 'name', '_line', 'locals')
  189. def __init__(self, filename, lineno, name, *, lookup_line=True,
  190. locals=None, line=None):
  191. """Construct a FrameSummary.
  192. :param lookup_line: If True, `linecache` is consulted for the source
  193. code line. Otherwise, the line will be looked up when first needed.
  194. :param locals: If supplied the frame locals, which will be captured as
  195. object representations.
  196. :param line: If provided, use this instead of looking up the line in
  197. the linecache.
  198. """
  199. self.filename = filename
  200. self.lineno = lineno
  201. self.name = name
  202. self._line = line
  203. if lookup_line:
  204. self.line
  205. self.locals = \
  206. dict((k, repr(v)) for k, v in locals.items()) if locals else None
  207. def __eq__(self, other):
  208. if isinstance(other, FrameSummary):
  209. return (self.filename == other.filename and
  210. self.lineno == other.lineno and
  211. self.name == other.name and
  212. self.locals == other.locals)
  213. if isinstance(other, tuple):
  214. return (self.filename, self.lineno, self.name, self.line) == other
  215. return NotImplemented
  216. def __getitem__(self, pos):
  217. return (self.filename, self.lineno, self.name, self.line)[pos]
  218. def __iter__(self):
  219. return iter([self.filename, self.lineno, self.name, self.line])
  220. def __repr__(self):
  221. return "<FrameSummary file {filename}, line {lineno} in {name}>".format(
  222. filename=self.filename, lineno=self.lineno, name=self.name)
  223. @property
  224. def line(self):
  225. if self._line is None:
  226. self._line = linecache.getline(self.filename, self.lineno).strip()
  227. return self._line
  228. def walk_stack(f):
  229. """Walk a stack yielding the frame and line number for each frame.
  230. This will follow f.f_back from the given frame. If no frame is given, the
  231. current stack is used. Usually used with StackSummary.extract.
  232. """
  233. if f is None:
  234. f = sys._getframe().f_back.f_back
  235. while f is not None:
  236. yield f, f.f_lineno
  237. f = f.f_back
  238. def walk_tb(tb):
  239. """Walk a traceback yielding the frame and line number for each frame.
  240. This will follow tb.tb_next (and thus is in the opposite order to
  241. walk_stack). Usually used with StackSummary.extract.
  242. """
  243. while tb is not None:
  244. yield tb.tb_frame, tb.tb_lineno
  245. tb = tb.tb_next
  246. class StackSummary(list):
  247. """A stack of frames."""
  248. @classmethod
  249. def extract(klass, frame_gen, *, limit=None, lookup_lines=True,
  250. capture_locals=False):
  251. """Create a StackSummary from a traceback or stack object.
  252. :param frame_gen: A generator that yields (frame, lineno) tuples to
  253. include in the stack.
  254. :param limit: None to include all frames or the number of frames to
  255. include.
  256. :param lookup_lines: If True, lookup lines for each frame immediately,
  257. otherwise lookup is deferred until the frame is rendered.
  258. :param capture_locals: If True, the local variables from each frame will
  259. be captured as object representations into the FrameSummary.
  260. """
  261. if limit is None:
  262. limit = getattr(sys, 'tracebacklimit', None)
  263. if limit is not None and limit < 0:
  264. limit = 0
  265. if limit is not None:
  266. if limit >= 0:
  267. frame_gen = itertools.islice(frame_gen, limit)
  268. else:
  269. frame_gen = collections.deque(frame_gen, maxlen=-limit)
  270. result = klass()
  271. fnames = set()
  272. for f, lineno in frame_gen:
  273. co = f.f_code
  274. filename = co.co_filename
  275. name = co.co_name
  276. fnames.add(filename)
  277. linecache.lazycache(filename, f.f_globals)
  278. # Must defer line lookups until we have called checkcache.
  279. if capture_locals:
  280. f_locals = f.f_locals
  281. else:
  282. f_locals = None
  283. result.append(FrameSummary(
  284. filename, lineno, name, lookup_line=False, locals=f_locals))
  285. for filename in fnames:
  286. linecache.checkcache(filename)
  287. # If immediate lookup was desired, trigger lookups now.
  288. if lookup_lines:
  289. for f in result:
  290. f.line
  291. return result
  292. @classmethod
  293. def from_list(klass, a_list):
  294. """Create a StackSummary from a simple list of tuples.
  295. This method supports the older Python API. Each tuple should be a
  296. 4-tuple with (filename, lineno, name, line) elements.
  297. """
  298. # While doing a fast-path check for isinstance(a_list, StackSummary) is
  299. # appealing, idlelib.run.cleanup_traceback and other similar code may
  300. # break this by making arbitrary frames plain tuples, so we need to
  301. # check on a frame by frame basis.
  302. result = StackSummary()
  303. for frame in a_list:
  304. if isinstance(frame, FrameSummary):
  305. result.append(frame)
  306. else:
  307. filename, lineno, name, line = frame
  308. result.append(FrameSummary(filename, lineno, name, line=line))
  309. return result
  310. def format(self):
  311. """Format the stack ready for printing.
  312. Returns a list of strings ready for printing. Each string in the
  313. resulting list corresponds to a single frame from the stack.
  314. Each string ends in a newline; the strings may contain internal
  315. newlines as well, for those items with source text lines.
  316. """
  317. result = []
  318. for frame in self:
  319. row = []
  320. row.append(' File "{}", line {}, in {}\n'.format(
  321. frame.filename, frame.lineno, frame.name))
  322. if frame.line:
  323. row.append(' {}\n'.format(frame.line.strip()))
  324. if frame.locals:
  325. for name, value in sorted(frame.locals.items()):
  326. row.append(' {name} = {value}\n'.format(name=name, value=value))
  327. result.append(''.join(row))
  328. return result
  329. class TracebackException:
  330. """An exception ready for rendering.
  331. The traceback module captures enough attributes from the original exception
  332. to this intermediary form to ensure that no references are held, while
  333. still being able to fully print or format it.
  334. Use `from_exception` to create TracebackException instances from exception
  335. objects, or the constructor to create TracebackException instances from
  336. individual components.
  337. - :attr:`__cause__` A TracebackException of the original *__cause__*.
  338. - :attr:`__context__` A TracebackException of the original *__context__*.
  339. - :attr:`__suppress_context__` The *__suppress_context__* value from the
  340. original exception.
  341. - :attr:`stack` A `StackSummary` representing the traceback.
  342. - :attr:`exc_type` The class of the original traceback.
  343. - :attr:`filename` For syntax errors - the filename where the error
  344. occurred.
  345. - :attr:`lineno` For syntax errors - the linenumber where the error
  346. occurred.
  347. - :attr:`text` For syntax errors - the text where the error
  348. occurred.
  349. - :attr:`offset` For syntax errors - the offset into the text where the
  350. error occurred.
  351. - :attr:`msg` For syntax errors - the compiler error message.
  352. """
  353. def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
  354. lookup_lines=True, capture_locals=False, _seen=None):
  355. # NB: we need to accept exc_traceback, exc_value, exc_traceback to
  356. # permit backwards compat with the existing API, otherwise we
  357. # need stub thunk objects just to glue it together.
  358. # Handle loops in __cause__ or __context__.
  359. if _seen is None:
  360. _seen = set()
  361. _seen.add(exc_value)
  362. # Gracefully handle (the way Python 2.4 and earlier did) the case of
  363. # being called with no type or value (None, None, None).
  364. if (exc_value and exc_value.__cause__ is not None
  365. and exc_value.__cause__ not in _seen):
  366. cause = TracebackException(
  367. type(exc_value.__cause__),
  368. exc_value.__cause__,
  369. exc_value.__cause__.__traceback__,
  370. limit=limit,
  371. lookup_lines=False,
  372. capture_locals=capture_locals,
  373. _seen=_seen)
  374. else:
  375. cause = None
  376. if (exc_value and exc_value.__context__ is not None
  377. and exc_value.__context__ not in _seen):
  378. context = TracebackException(
  379. type(exc_value.__context__),
  380. exc_value.__context__,
  381. exc_value.__context__.__traceback__,
  382. limit=limit,
  383. lookup_lines=False,
  384. capture_locals=capture_locals,
  385. _seen=_seen)
  386. else:
  387. context = None
  388. self.exc_traceback = exc_traceback
  389. self.__cause__ = cause
  390. self.__context__ = context
  391. self.__suppress_context__ = \
  392. exc_value.__suppress_context__ if exc_value else False
  393. # TODO: locals.
  394. self.stack = StackSummary.extract(
  395. walk_tb(exc_traceback), limit=limit, lookup_lines=lookup_lines,
  396. capture_locals=capture_locals)
  397. self.exc_type = exc_type
  398. # Capture now to permit freeing resources: only complication is in the
  399. # unofficial API _format_final_exc_line
  400. self._str = _some_str(exc_value)
  401. if exc_type and issubclass(exc_type, SyntaxError):
  402. # Handle SyntaxError's specially
  403. self.filename = exc_value.filename
  404. self.lineno = str(exc_value.lineno)
  405. self.text = exc_value.text
  406. self.offset = exc_value.offset
  407. self.msg = exc_value.msg
  408. if lookup_lines:
  409. self._load_lines()
  410. @classmethod
  411. def from_exception(self, exc, *args, **kwargs):
  412. """Create a TracebackException from an exception."""
  413. return TracebackException(
  414. type(exc), exc, exc.__traceback__, *args, **kwargs)
  415. def _load_lines(self):
  416. """Private API. force all lines in the stack to be loaded."""
  417. for frame in self.stack:
  418. frame.line
  419. if self.__context__:
  420. self.__context__._load_lines()
  421. if self.__cause__:
  422. self.__cause__._load_lines()
  423. def __eq__(self, other):
  424. return self.__dict__ == other.__dict__
  425. def __str__(self):
  426. return self._str
  427. def format_exception_only(self):
  428. """Format the exception part of the traceback.
  429. The return value is a generator of strings, each ending in a newline.
  430. Normally, the generator emits a single string; however, for
  431. SyntaxError exceptions, it emites several lines that (when
  432. printed) display detailed information about where the syntax
  433. error occurred.
  434. The message indicating which exception occurred is always the last
  435. string in the output.
  436. """
  437. if self.exc_type is None:
  438. yield _format_final_exc_line(None, self._str)
  439. return
  440. stype = self.exc_type.__qualname__
  441. smod = self.exc_type.__module__
  442. if smod not in ("__main__", "builtins"):
  443. stype = smod + '.' + stype
  444. if not issubclass(self.exc_type, SyntaxError):
  445. yield _format_final_exc_line(stype, self._str)
  446. return
  447. # It was a syntax error; show exactly where the problem was found.
  448. filename = self.filename or "<string>"
  449. lineno = str(self.lineno) or '?'
  450. yield ' File "{}", line {}\n'.format(filename, lineno)
  451. badline = self.text
  452. offset = self.offset
  453. if badline is not None:
  454. yield ' {}\n'.format(badline.strip())
  455. if offset is not None:
  456. caretspace = badline.rstrip('\n')
  457. offset = min(len(caretspace), offset) - 1
  458. caretspace = caretspace[:offset].lstrip()
  459. # non-space whitespace (likes tabs) must be kept for alignment
  460. caretspace = ((c.isspace() and c or ' ') for c in caretspace)
  461. yield ' {}^\n'.format(''.join(caretspace))
  462. msg = self.msg or "<no detail available>"
  463. yield "{}: {}\n".format(stype, msg)
  464. def format(self, *, chain=True):
  465. """Format the exception.
  466. If chain is not *True*, *__cause__* and *__context__* will not be formatted.
  467. The return value is a generator of strings, each ending in a newline and
  468. some containing internal newlines. `print_exception` is a wrapper around
  469. this method which just prints the lines to a file.
  470. The message indicating which exception occurred is always the last
  471. string in the output.
  472. """
  473. if chain:
  474. if self.__cause__ is not None:
  475. yield from self.__cause__.format(chain=chain)
  476. yield _cause_message
  477. elif (self.__context__ is not None and
  478. not self.__suppress_context__):
  479. yield from self.__context__.format(chain=chain)
  480. yield _context_message
  481. if self.exc_traceback is not None:
  482. yield 'Traceback (most recent call last):\n'
  483. yield from self.stack.format()
  484. yield from self.format_exception_only()