traceback.py 31 KB

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