traceback.py 24 KB

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