traceback.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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. if (exc_value and exc_value.__cause__ is not None
  399. and id(exc_value.__cause__) not in _seen):
  400. cause = TracebackException(
  401. type(exc_value.__cause__),
  402. exc_value.__cause__,
  403. exc_value.__cause__.__traceback__,
  404. limit=limit,
  405. lookup_lines=False,
  406. capture_locals=capture_locals,
  407. _seen=_seen)
  408. else:
  409. cause = None
  410. if (exc_value and exc_value.__context__ is not None
  411. and id(exc_value.__context__) not in _seen):
  412. context = TracebackException(
  413. type(exc_value.__context__),
  414. exc_value.__context__,
  415. exc_value.__context__.__traceback__,
  416. limit=limit,
  417. lookup_lines=False,
  418. capture_locals=capture_locals,
  419. _seen=_seen)
  420. else:
  421. context = None
  422. self.__cause__ = cause
  423. self.__context__ = context
  424. self.__suppress_context__ = \
  425. exc_value.__suppress_context__ if exc_value else False
  426. # TODO: locals.
  427. self.stack = StackSummary.extract(
  428. walk_tb(exc_traceback), limit=limit, lookup_lines=lookup_lines,
  429. capture_locals=capture_locals)
  430. self.exc_type = exc_type
  431. # Capture now to permit freeing resources: only complication is in the
  432. # unofficial API _format_final_exc_line
  433. self._str = _some_str(exc_value)
  434. if exc_type and issubclass(exc_type, SyntaxError):
  435. # Handle SyntaxError's specially
  436. self.filename = exc_value.filename
  437. self.lineno = str(exc_value.lineno)
  438. self.text = exc_value.text
  439. self.offset = exc_value.offset
  440. self.msg = exc_value.msg
  441. if lookup_lines:
  442. self._load_lines()
  443. @classmethod
  444. def from_exception(cls, exc, *args, **kwargs):
  445. """Create a TracebackException from an exception."""
  446. return cls(type(exc), exc, exc.__traceback__, *args, **kwargs)
  447. def _load_lines(self):
  448. """Private API. force all lines in the stack to be loaded."""
  449. for frame in self.stack:
  450. frame.line
  451. if self.__context__:
  452. self.__context__._load_lines()
  453. if self.__cause__:
  454. self.__cause__._load_lines()
  455. def __eq__(self, other):
  456. return self.__dict__ == other.__dict__
  457. def __str__(self):
  458. return self._str
  459. def format_exception_only(self):
  460. """Format the exception part of the traceback.
  461. The return value is a generator of strings, each ending in a newline.
  462. Normally, the generator emits a single string; however, for
  463. SyntaxError exceptions, it emits several lines that (when
  464. printed) display detailed information about where the syntax
  465. error occurred.
  466. The message indicating which exception occurred is always the last
  467. string in the output.
  468. """
  469. if self.exc_type is None:
  470. yield _format_final_exc_line(None, self._str)
  471. return
  472. stype = self.exc_type.__qualname__
  473. smod = self.exc_type.__module__
  474. if smod not in ("__main__", "builtins"):
  475. stype = smod + '.' + stype
  476. if not issubclass(self.exc_type, SyntaxError):
  477. yield _format_final_exc_line(stype, self._str)
  478. return
  479. # It was a syntax error; show exactly where the problem was found.
  480. filename = self.filename or "<string>"
  481. lineno = str(self.lineno) or '?'
  482. yield ' File "{}", line {}\n'.format(filename, lineno)
  483. badline = self.text
  484. offset = self.offset
  485. if badline is not None:
  486. yield ' {}\n'.format(badline.strip())
  487. if offset is not None:
  488. caretspace = badline.rstrip('\n')
  489. offset = min(len(caretspace), offset) - 1
  490. caretspace = caretspace[:offset].lstrip()
  491. # non-space whitespace (likes tabs) must be kept for alignment
  492. caretspace = ((c.isspace() and c or ' ') for c in caretspace)
  493. yield ' {}^\n'.format(''.join(caretspace))
  494. msg = self.msg or "<no detail available>"
  495. yield "{}: {}\n".format(stype, msg)
  496. def format(self, *, chain=True):
  497. """Format the exception.
  498. If chain is not *True*, *__cause__* and *__context__* will not be formatted.
  499. The return value is a generator of strings, each ending in a newline and
  500. some containing internal newlines. `print_exception` is a wrapper around
  501. this method which just prints the lines to a file.
  502. The message indicating which exception occurred is always the last
  503. string in the output.
  504. """
  505. if chain:
  506. if self.__cause__ is not None:
  507. yield from self.__cause__.format(chain=chain)
  508. yield _cause_message
  509. elif (self.__context__ is not None and
  510. not self.__suppress_context__):
  511. yield from self.__context__.format(chain=chain)
  512. yield _context_message
  513. if self.stack:
  514. yield 'Traceback (most recent call last):\n'
  515. yield from self.stack.format()
  516. yield from self.format_exception_only()