traceback.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. from __future__ import absolute_import
  2. import linecache
  3. import os
  4. import platform
  5. import sys
  6. from dataclasses import dataclass, field
  7. from traceback import walk_tb
  8. from types import ModuleType, TracebackType
  9. from typing import (
  10. Any,
  11. Callable,
  12. Dict,
  13. Iterable,
  14. List,
  15. Optional,
  16. Sequence,
  17. Tuple,
  18. Type,
  19. Union,
  20. )
  21. from pip._vendor.pygments.lexers import guess_lexer_for_filename
  22. from pip._vendor.pygments.token import Comment, Keyword, Name, Number, Operator, String
  23. from pip._vendor.pygments.token import Text as TextToken
  24. from pip._vendor.pygments.token import Token
  25. from pip._vendor.pygments.util import ClassNotFound
  26. from . import pretty
  27. from ._loop import loop_last
  28. from .columns import Columns
  29. from .console import Console, ConsoleOptions, ConsoleRenderable, RenderResult, group
  30. from .constrain import Constrain
  31. from .highlighter import RegexHighlighter, ReprHighlighter
  32. from .panel import Panel
  33. from .scope import render_scope
  34. from .style import Style
  35. from .syntax import Syntax
  36. from .text import Text
  37. from .theme import Theme
  38. WINDOWS = platform.system() == "Windows"
  39. LOCALS_MAX_LENGTH = 10
  40. LOCALS_MAX_STRING = 80
  41. def install(
  42. *,
  43. console: Optional[Console] = None,
  44. width: Optional[int] = 100,
  45. extra_lines: int = 3,
  46. theme: Optional[str] = None,
  47. word_wrap: bool = False,
  48. show_locals: bool = False,
  49. locals_max_length: int = LOCALS_MAX_LENGTH,
  50. locals_max_string: int = LOCALS_MAX_STRING,
  51. locals_hide_dunder: bool = True,
  52. locals_hide_sunder: Optional[bool] = None,
  53. indent_guides: bool = True,
  54. suppress: Iterable[Union[str, ModuleType]] = (),
  55. max_frames: int = 100,
  56. ) -> Callable[[Type[BaseException], BaseException, Optional[TracebackType]], Any]:
  57. """Install a rich traceback handler.
  58. Once installed, any tracebacks will be printed with syntax highlighting and rich formatting.
  59. Args:
  60. console (Optional[Console], optional): Console to write exception to. Default uses internal Console instance.
  61. width (Optional[int], optional): Width (in characters) of traceback. Defaults to 100.
  62. extra_lines (int, optional): Extra lines of code. Defaults to 3.
  63. theme (Optional[str], optional): Pygments theme to use in traceback. Defaults to ``None`` which will pick
  64. a theme appropriate for the platform.
  65. word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
  66. show_locals (bool, optional): Enable display of local variables. Defaults to False.
  67. locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
  68. Defaults to 10.
  69. locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
  70. locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
  71. locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
  72. indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
  73. suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
  74. Returns:
  75. Callable: The previous exception handler that was replaced.
  76. """
  77. traceback_console = Console(stderr=True) if console is None else console
  78. locals_hide_sunder = (
  79. True
  80. if (traceback_console.is_jupyter and locals_hide_sunder is None)
  81. else locals_hide_sunder
  82. )
  83. def excepthook(
  84. type_: Type[BaseException],
  85. value: BaseException,
  86. traceback: Optional[TracebackType],
  87. ) -> None:
  88. traceback_console.print(
  89. Traceback.from_exception(
  90. type_,
  91. value,
  92. traceback,
  93. width=width,
  94. extra_lines=extra_lines,
  95. theme=theme,
  96. word_wrap=word_wrap,
  97. show_locals=show_locals,
  98. locals_max_length=locals_max_length,
  99. locals_max_string=locals_max_string,
  100. locals_hide_dunder=locals_hide_dunder,
  101. locals_hide_sunder=bool(locals_hide_sunder),
  102. indent_guides=indent_guides,
  103. suppress=suppress,
  104. max_frames=max_frames,
  105. )
  106. )
  107. def ipy_excepthook_closure(ip: Any) -> None: # pragma: no cover
  108. tb_data = {} # store information about showtraceback call
  109. default_showtraceback = ip.showtraceback # keep reference of default traceback
  110. def ipy_show_traceback(*args: Any, **kwargs: Any) -> None:
  111. """wrap the default ip.showtraceback to store info for ip._showtraceback"""
  112. nonlocal tb_data
  113. tb_data = kwargs
  114. default_showtraceback(*args, **kwargs)
  115. def ipy_display_traceback(
  116. *args: Any, is_syntax: bool = False, **kwargs: Any
  117. ) -> None:
  118. """Internally called traceback from ip._showtraceback"""
  119. nonlocal tb_data
  120. exc_tuple = ip._get_exc_info()
  121. # do not display trace on syntax error
  122. tb: Optional[TracebackType] = None if is_syntax else exc_tuple[2]
  123. # determine correct tb_offset
  124. compiled = tb_data.get("running_compiled_code", False)
  125. tb_offset = tb_data.get("tb_offset", 1 if compiled else 0)
  126. # remove ipython internal frames from trace with tb_offset
  127. for _ in range(tb_offset):
  128. if tb is None:
  129. break
  130. tb = tb.tb_next
  131. excepthook(exc_tuple[0], exc_tuple[1], tb)
  132. tb_data = {} # clear data upon usage
  133. # replace _showtraceback instead of showtraceback to allow ipython features such as debugging to work
  134. # this is also what the ipython docs recommends to modify when subclassing InteractiveShell
  135. ip._showtraceback = ipy_display_traceback
  136. # add wrapper to capture tb_data
  137. ip.showtraceback = ipy_show_traceback
  138. ip.showsyntaxerror = lambda *args, **kwargs: ipy_display_traceback(
  139. *args, is_syntax=True, **kwargs
  140. )
  141. try: # pragma: no cover
  142. # if within ipython, use customized traceback
  143. ip = get_ipython() # type: ignore[name-defined]
  144. ipy_excepthook_closure(ip)
  145. return sys.excepthook
  146. except Exception:
  147. # otherwise use default system hook
  148. old_excepthook = sys.excepthook
  149. sys.excepthook = excepthook
  150. return old_excepthook
  151. @dataclass
  152. class Frame:
  153. filename: str
  154. lineno: int
  155. name: str
  156. line: str = ""
  157. locals: Optional[Dict[str, pretty.Node]] = None
  158. @dataclass
  159. class _SyntaxError:
  160. offset: int
  161. filename: str
  162. line: str
  163. lineno: int
  164. msg: str
  165. @dataclass
  166. class Stack:
  167. exc_type: str
  168. exc_value: str
  169. syntax_error: Optional[_SyntaxError] = None
  170. is_cause: bool = False
  171. frames: List[Frame] = field(default_factory=list)
  172. @dataclass
  173. class Trace:
  174. stacks: List[Stack]
  175. class PathHighlighter(RegexHighlighter):
  176. highlights = [r"(?P<dim>.*/)(?P<bold>.+)"]
  177. class Traceback:
  178. """A Console renderable that renders a traceback.
  179. Args:
  180. trace (Trace, optional): A `Trace` object produced from `extract`. Defaults to None, which uses
  181. the last exception.
  182. width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.
  183. extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
  184. theme (str, optional): Override pygments theme used in traceback.
  185. word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
  186. show_locals (bool, optional): Enable display of local variables. Defaults to False.
  187. indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
  188. locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
  189. Defaults to 10.
  190. locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
  191. locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
  192. locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
  193. suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
  194. max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.
  195. """
  196. LEXERS = {
  197. "": "text",
  198. ".py": "python",
  199. ".pxd": "cython",
  200. ".pyx": "cython",
  201. ".pxi": "pyrex",
  202. }
  203. def __init__(
  204. self,
  205. trace: Optional[Trace] = None,
  206. *,
  207. width: Optional[int] = 100,
  208. extra_lines: int = 3,
  209. theme: Optional[str] = None,
  210. word_wrap: bool = False,
  211. show_locals: bool = False,
  212. locals_max_length: int = LOCALS_MAX_LENGTH,
  213. locals_max_string: int = LOCALS_MAX_STRING,
  214. locals_hide_dunder: bool = True,
  215. locals_hide_sunder: bool = False,
  216. indent_guides: bool = True,
  217. suppress: Iterable[Union[str, ModuleType]] = (),
  218. max_frames: int = 100,
  219. ):
  220. if trace is None:
  221. exc_type, exc_value, traceback = sys.exc_info()
  222. if exc_type is None or exc_value is None or traceback is None:
  223. raise ValueError(
  224. "Value for 'trace' required if not called in except: block"
  225. )
  226. trace = self.extract(
  227. exc_type, exc_value, traceback, show_locals=show_locals
  228. )
  229. self.trace = trace
  230. self.width = width
  231. self.extra_lines = extra_lines
  232. self.theme = Syntax.get_theme(theme or "ansi_dark")
  233. self.word_wrap = word_wrap
  234. self.show_locals = show_locals
  235. self.indent_guides = indent_guides
  236. self.locals_max_length = locals_max_length
  237. self.locals_max_string = locals_max_string
  238. self.locals_hide_dunder = locals_hide_dunder
  239. self.locals_hide_sunder = locals_hide_sunder
  240. self.suppress: Sequence[str] = []
  241. for suppress_entity in suppress:
  242. if not isinstance(suppress_entity, str):
  243. assert (
  244. suppress_entity.__file__ is not None
  245. ), f"{suppress_entity!r} must be a module with '__file__' attribute"
  246. path = os.path.dirname(suppress_entity.__file__)
  247. else:
  248. path = suppress_entity
  249. path = os.path.normpath(os.path.abspath(path))
  250. self.suppress.append(path)
  251. self.max_frames = max(4, max_frames) if max_frames > 0 else 0
  252. @classmethod
  253. def from_exception(
  254. cls,
  255. exc_type: Type[Any],
  256. exc_value: BaseException,
  257. traceback: Optional[TracebackType],
  258. *,
  259. width: Optional[int] = 100,
  260. extra_lines: int = 3,
  261. theme: Optional[str] = None,
  262. word_wrap: bool = False,
  263. show_locals: bool = False,
  264. locals_max_length: int = LOCALS_MAX_LENGTH,
  265. locals_max_string: int = LOCALS_MAX_STRING,
  266. locals_hide_dunder: bool = True,
  267. locals_hide_sunder: bool = False,
  268. indent_guides: bool = True,
  269. suppress: Iterable[Union[str, ModuleType]] = (),
  270. max_frames: int = 100,
  271. ) -> "Traceback":
  272. """Create a traceback from exception info
  273. Args:
  274. exc_type (Type[BaseException]): Exception type.
  275. exc_value (BaseException): Exception value.
  276. traceback (TracebackType): Python Traceback object.
  277. width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.
  278. extra_lines (int, optional): Additional lines of code to render. Defaults to 3.
  279. theme (str, optional): Override pygments theme used in traceback.
  280. word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.
  281. show_locals (bool, optional): Enable display of local variables. Defaults to False.
  282. indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.
  283. locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
  284. Defaults to 10.
  285. locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
  286. locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
  287. locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
  288. suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.
  289. max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.
  290. Returns:
  291. Traceback: A Traceback instance that may be printed.
  292. """
  293. rich_traceback = cls.extract(
  294. exc_type,
  295. exc_value,
  296. traceback,
  297. show_locals=show_locals,
  298. locals_max_length=locals_max_length,
  299. locals_max_string=locals_max_string,
  300. locals_hide_dunder=locals_hide_dunder,
  301. locals_hide_sunder=locals_hide_sunder,
  302. )
  303. return cls(
  304. rich_traceback,
  305. width=width,
  306. extra_lines=extra_lines,
  307. theme=theme,
  308. word_wrap=word_wrap,
  309. show_locals=show_locals,
  310. indent_guides=indent_guides,
  311. locals_max_length=locals_max_length,
  312. locals_max_string=locals_max_string,
  313. locals_hide_dunder=locals_hide_dunder,
  314. locals_hide_sunder=locals_hide_sunder,
  315. suppress=suppress,
  316. max_frames=max_frames,
  317. )
  318. @classmethod
  319. def extract(
  320. cls,
  321. exc_type: Type[BaseException],
  322. exc_value: BaseException,
  323. traceback: Optional[TracebackType],
  324. *,
  325. show_locals: bool = False,
  326. locals_max_length: int = LOCALS_MAX_LENGTH,
  327. locals_max_string: int = LOCALS_MAX_STRING,
  328. locals_hide_dunder: bool = True,
  329. locals_hide_sunder: bool = False,
  330. ) -> Trace:
  331. """Extract traceback information.
  332. Args:
  333. exc_type (Type[BaseException]): Exception type.
  334. exc_value (BaseException): Exception value.
  335. traceback (TracebackType): Python Traceback object.
  336. show_locals (bool, optional): Enable display of local variables. Defaults to False.
  337. locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.
  338. Defaults to 10.
  339. locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.
  340. locals_hide_dunder (bool, optional): Hide locals prefixed with double underscore. Defaults to True.
  341. locals_hide_sunder (bool, optional): Hide locals prefixed with single underscore. Defaults to False.
  342. Returns:
  343. Trace: A Trace instance which you can use to construct a `Traceback`.
  344. """
  345. stacks: List[Stack] = []
  346. is_cause = False
  347. from pip._vendor.rich import _IMPORT_CWD
  348. def safe_str(_object: Any) -> str:
  349. """Don't allow exceptions from __str__ to propagate."""
  350. try:
  351. return str(_object)
  352. except Exception:
  353. return "<exception str() failed>"
  354. while True:
  355. stack = Stack(
  356. exc_type=safe_str(exc_type.__name__),
  357. exc_value=safe_str(exc_value),
  358. is_cause=is_cause,
  359. )
  360. if isinstance(exc_value, SyntaxError):
  361. stack.syntax_error = _SyntaxError(
  362. offset=exc_value.offset or 0,
  363. filename=exc_value.filename or "?",
  364. lineno=exc_value.lineno or 0,
  365. line=exc_value.text or "",
  366. msg=exc_value.msg,
  367. )
  368. stacks.append(stack)
  369. append = stack.frames.append
  370. def get_locals(
  371. iter_locals: Iterable[Tuple[str, object]]
  372. ) -> Iterable[Tuple[str, object]]:
  373. """Extract locals from an iterator of key pairs."""
  374. if not (locals_hide_dunder or locals_hide_sunder):
  375. yield from iter_locals
  376. return
  377. for key, value in iter_locals:
  378. if locals_hide_dunder and key.startswith("__"):
  379. continue
  380. if locals_hide_sunder and key.startswith("_"):
  381. continue
  382. yield key, value
  383. for frame_summary, line_no in walk_tb(traceback):
  384. filename = frame_summary.f_code.co_filename
  385. if filename and not filename.startswith("<"):
  386. if not os.path.isabs(filename):
  387. filename = os.path.join(_IMPORT_CWD, filename)
  388. if frame_summary.f_locals.get("_rich_traceback_omit", False):
  389. continue
  390. frame = Frame(
  391. filename=filename or "?",
  392. lineno=line_no,
  393. name=frame_summary.f_code.co_name,
  394. locals={
  395. key: pretty.traverse(
  396. value,
  397. max_length=locals_max_length,
  398. max_string=locals_max_string,
  399. )
  400. for key, value in get_locals(frame_summary.f_locals.items())
  401. }
  402. if show_locals
  403. else None,
  404. )
  405. append(frame)
  406. if frame_summary.f_locals.get("_rich_traceback_guard", False):
  407. del stack.frames[:]
  408. cause = getattr(exc_value, "__cause__", None)
  409. if cause:
  410. exc_type = cause.__class__
  411. exc_value = cause
  412. # __traceback__ can be None, e.g. for exceptions raised by the
  413. # 'multiprocessing' module
  414. traceback = cause.__traceback__
  415. is_cause = True
  416. continue
  417. cause = exc_value.__context__
  418. if cause and not getattr(exc_value, "__suppress_context__", False):
  419. exc_type = cause.__class__
  420. exc_value = cause
  421. traceback = cause.__traceback__
  422. is_cause = False
  423. continue
  424. # No cover, code is reached but coverage doesn't recognize it.
  425. break # pragma: no cover
  426. trace = Trace(stacks=stacks)
  427. return trace
  428. def __rich_console__(
  429. self, console: Console, options: ConsoleOptions
  430. ) -> RenderResult:
  431. theme = self.theme
  432. background_style = theme.get_background_style()
  433. token_style = theme.get_style_for_token
  434. traceback_theme = Theme(
  435. {
  436. "pretty": token_style(TextToken),
  437. "pygments.text": token_style(Token),
  438. "pygments.string": token_style(String),
  439. "pygments.function": token_style(Name.Function),
  440. "pygments.number": token_style(Number),
  441. "repr.indent": token_style(Comment) + Style(dim=True),
  442. "repr.str": token_style(String),
  443. "repr.brace": token_style(TextToken) + Style(bold=True),
  444. "repr.number": token_style(Number),
  445. "repr.bool_true": token_style(Keyword.Constant),
  446. "repr.bool_false": token_style(Keyword.Constant),
  447. "repr.none": token_style(Keyword.Constant),
  448. "scope.border": token_style(String.Delimiter),
  449. "scope.equals": token_style(Operator),
  450. "scope.key": token_style(Name),
  451. "scope.key.special": token_style(Name.Constant) + Style(dim=True),
  452. },
  453. inherit=False,
  454. )
  455. highlighter = ReprHighlighter()
  456. for last, stack in loop_last(reversed(self.trace.stacks)):
  457. if stack.frames:
  458. stack_renderable: ConsoleRenderable = Panel(
  459. self._render_stack(stack),
  460. title="[traceback.title]Traceback [dim](most recent call last)",
  461. style=background_style,
  462. border_style="traceback.border",
  463. expand=True,
  464. padding=(0, 1),
  465. )
  466. stack_renderable = Constrain(stack_renderable, self.width)
  467. with console.use_theme(traceback_theme):
  468. yield stack_renderable
  469. if stack.syntax_error is not None:
  470. with console.use_theme(traceback_theme):
  471. yield Constrain(
  472. Panel(
  473. self._render_syntax_error(stack.syntax_error),
  474. style=background_style,
  475. border_style="traceback.border.syntax_error",
  476. expand=True,
  477. padding=(0, 1),
  478. width=self.width,
  479. ),
  480. self.width,
  481. )
  482. yield Text.assemble(
  483. (f"{stack.exc_type}: ", "traceback.exc_type"),
  484. highlighter(stack.syntax_error.msg),
  485. )
  486. elif stack.exc_value:
  487. yield Text.assemble(
  488. (f"{stack.exc_type}: ", "traceback.exc_type"),
  489. highlighter(stack.exc_value),
  490. )
  491. else:
  492. yield Text.assemble((f"{stack.exc_type}", "traceback.exc_type"))
  493. if not last:
  494. if stack.is_cause:
  495. yield Text.from_markup(
  496. "\n[i]The above exception was the direct cause of the following exception:\n",
  497. )
  498. else:
  499. yield Text.from_markup(
  500. "\n[i]During handling of the above exception, another exception occurred:\n",
  501. )
  502. @group()
  503. def _render_syntax_error(self, syntax_error: _SyntaxError) -> RenderResult:
  504. highlighter = ReprHighlighter()
  505. path_highlighter = PathHighlighter()
  506. if syntax_error.filename != "<stdin>":
  507. if os.path.exists(syntax_error.filename):
  508. text = Text.assemble(
  509. (f" {syntax_error.filename}", "pygments.string"),
  510. (":", "pygments.text"),
  511. (str(syntax_error.lineno), "pygments.number"),
  512. style="pygments.text",
  513. )
  514. yield path_highlighter(text)
  515. syntax_error_text = highlighter(syntax_error.line.rstrip())
  516. syntax_error_text.no_wrap = True
  517. offset = min(syntax_error.offset - 1, len(syntax_error_text))
  518. syntax_error_text.stylize("bold underline", offset, offset)
  519. syntax_error_text += Text.from_markup(
  520. "\n" + " " * offset + "[traceback.offset]▲[/]",
  521. style="pygments.text",
  522. )
  523. yield syntax_error_text
  524. @classmethod
  525. def _guess_lexer(cls, filename: str, code: str) -> str:
  526. ext = os.path.splitext(filename)[-1]
  527. if not ext:
  528. # No extension, look at first line to see if it is a hashbang
  529. # Note, this is an educated guess and not a guarantee
  530. # If it fails, the only downside is that the code is highlighted strangely
  531. new_line_index = code.index("\n")
  532. first_line = code[:new_line_index] if new_line_index != -1 else code
  533. if first_line.startswith("#!") and "python" in first_line.lower():
  534. return "python"
  535. try:
  536. return cls.LEXERS.get(ext) or guess_lexer_for_filename(filename, code).name
  537. except ClassNotFound:
  538. return "text"
  539. @group()
  540. def _render_stack(self, stack: Stack) -> RenderResult:
  541. path_highlighter = PathHighlighter()
  542. theme = self.theme
  543. def read_code(filename: str) -> str:
  544. """Read files, and cache results on filename.
  545. Args:
  546. filename (str): Filename to read
  547. Returns:
  548. str: Contents of file
  549. """
  550. return "".join(linecache.getlines(filename))
  551. def render_locals(frame: Frame) -> Iterable[ConsoleRenderable]:
  552. if frame.locals:
  553. yield render_scope(
  554. frame.locals,
  555. title="locals",
  556. indent_guides=self.indent_guides,
  557. max_length=self.locals_max_length,
  558. max_string=self.locals_max_string,
  559. )
  560. exclude_frames: Optional[range] = None
  561. if self.max_frames != 0:
  562. exclude_frames = range(
  563. self.max_frames // 2,
  564. len(stack.frames) - self.max_frames // 2,
  565. )
  566. excluded = False
  567. for frame_index, frame in enumerate(stack.frames):
  568. if exclude_frames and frame_index in exclude_frames:
  569. excluded = True
  570. continue
  571. if excluded:
  572. assert exclude_frames is not None
  573. yield Text(
  574. f"\n... {len(exclude_frames)} frames hidden ...",
  575. justify="center",
  576. style="traceback.error",
  577. )
  578. excluded = False
  579. first = frame_index == 0
  580. frame_filename = frame.filename
  581. suppressed = any(frame_filename.startswith(path) for path in self.suppress)
  582. if os.path.exists(frame.filename):
  583. text = Text.assemble(
  584. path_highlighter(Text(frame.filename, style="pygments.string")),
  585. (":", "pygments.text"),
  586. (str(frame.lineno), "pygments.number"),
  587. " in ",
  588. (frame.name, "pygments.function"),
  589. style="pygments.text",
  590. )
  591. else:
  592. text = Text.assemble(
  593. "in ",
  594. (frame.name, "pygments.function"),
  595. (":", "pygments.text"),
  596. (str(frame.lineno), "pygments.number"),
  597. style="pygments.text",
  598. )
  599. if not frame.filename.startswith("<") and not first:
  600. yield ""
  601. yield text
  602. if frame.filename.startswith("<"):
  603. yield from render_locals(frame)
  604. continue
  605. if not suppressed:
  606. try:
  607. code = read_code(frame.filename)
  608. if not code:
  609. # code may be an empty string if the file doesn't exist, OR
  610. # if the traceback filename is generated dynamically
  611. continue
  612. lexer_name = self._guess_lexer(frame.filename, code)
  613. syntax = Syntax(
  614. code,
  615. lexer_name,
  616. theme=theme,
  617. line_numbers=True,
  618. line_range=(
  619. frame.lineno - self.extra_lines,
  620. frame.lineno + self.extra_lines,
  621. ),
  622. highlight_lines={frame.lineno},
  623. word_wrap=self.word_wrap,
  624. code_width=88,
  625. indent_guides=self.indent_guides,
  626. dedent=False,
  627. )
  628. yield ""
  629. except Exception as error:
  630. yield Text.assemble(
  631. (f"\n{error}", "traceback.error"),
  632. )
  633. else:
  634. yield (
  635. Columns(
  636. [
  637. syntax,
  638. *render_locals(frame),
  639. ],
  640. padding=1,
  641. )
  642. if frame.locals
  643. else syntax
  644. )
  645. if __name__ == "__main__": # pragma: no cover
  646. from .console import Console
  647. console = Console()
  648. import sys
  649. def bar(a: Any) -> None: # 这是对亚洲语言支持的测试。面对模棱两可的想法,拒绝猜测的诱惑
  650. one = 1
  651. print(one / a)
  652. def foo(a: Any) -> None:
  653. _rich_traceback_guard = True
  654. zed = {
  655. "characters": {
  656. "Paul Atreides",
  657. "Vladimir Harkonnen",
  658. "Thufir Hawat",
  659. "Duncan Idaho",
  660. },
  661. "atomic_types": (None, False, True),
  662. }
  663. bar(a)
  664. def error() -> None:
  665. try:
  666. try:
  667. foo(0)
  668. except:
  669. slfkjsldkfj # type: ignore[name-defined]
  670. except:
  671. console.print_exception(show_locals=True)
  672. error()