logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

traceback.py (26136B)


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