ultratb.py 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525
  1. # -*- coding: utf-8 -*-
  2. """
  3. Verbose and colourful traceback formatting.
  4. **ColorTB**
  5. I've always found it a bit hard to visually parse tracebacks in Python. The
  6. ColorTB class is a solution to that problem. It colors the different parts of a
  7. traceback in a manner similar to what you would expect from a syntax-highlighting
  8. text editor.
  9. Installation instructions for ColorTB::
  10. import sys,ultratb
  11. sys.excepthook = ultratb.ColorTB()
  12. **VerboseTB**
  13. I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
  14. of useful info when a traceback occurs. Ping originally had it spit out HTML
  15. and intended it for CGI programmers, but why should they have all the fun? I
  16. altered it to spit out colored text to the terminal. It's a bit overwhelming,
  17. but kind of neat, and maybe useful for long-running programs that you believe
  18. are bug-free. If a crash *does* occur in that type of program you want details.
  19. Give it a shot--you'll love it or you'll hate it.
  20. .. note::
  21. The Verbose mode prints the variables currently visible where the exception
  22. happened (shortening their strings if too long). This can potentially be
  23. very slow, if you happen to have a huge data structure whose string
  24. representation is complex to compute. Your computer may appear to freeze for
  25. a while with cpu usage at 100%. If this occurs, you can cancel the traceback
  26. with Ctrl-C (maybe hitting it more than once).
  27. If you encounter this kind of situation often, you may want to use the
  28. Verbose_novars mode instead of the regular Verbose, which avoids formatting
  29. variables (but otherwise includes the information and context given by
  30. Verbose).
  31. .. note::
  32. The verbose mode print all variables in the stack, which means it can
  33. potentially leak sensitive information like access keys, or unencrypted
  34. password.
  35. Installation instructions for VerboseTB::
  36. import sys,ultratb
  37. sys.excepthook = ultratb.VerboseTB()
  38. Note: Much of the code in this module was lifted verbatim from the standard
  39. library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
  40. Color schemes
  41. -------------
  42. The colors are defined in the class TBTools through the use of the
  43. ColorSchemeTable class. Currently the following exist:
  44. - NoColor: allows all of this module to be used in any terminal (the color
  45. escapes are just dummy blank strings).
  46. - Linux: is meant to look good in a terminal like the Linux console (black
  47. or very dark background).
  48. - LightBG: similar to Linux but swaps dark/light colors to be more readable
  49. in light background terminals.
  50. - Neutral: a neutral color scheme that should be readable on both light and
  51. dark background
  52. You can implement other color schemes easily, the syntax is fairly
  53. self-explanatory. Please send back new schemes you develop to the author for
  54. possible inclusion in future releases.
  55. Inheritance diagram:
  56. .. inheritance-diagram:: IPython.core.ultratb
  57. :parts: 3
  58. """
  59. #*****************************************************************************
  60. # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
  61. # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
  62. #
  63. # Distributed under the terms of the BSD License. The full license is in
  64. # the file COPYING, distributed as part of this software.
  65. #*****************************************************************************
  66. from collections.abc import Sequence
  67. import functools
  68. import inspect
  69. import linecache
  70. import pydoc
  71. import sys
  72. import time
  73. import traceback
  74. import types
  75. from types import TracebackType
  76. from typing import Any, List, Optional, Tuple
  77. import stack_data
  78. from pygments.formatters.terminal256 import Terminal256Formatter
  79. from pygments.styles import get_style_by_name
  80. import IPython.utils.colorable as colorable
  81. # IPython's own modules
  82. from IPython import get_ipython
  83. from IPython.core import debugger
  84. from IPython.core.display_trap import DisplayTrap
  85. from IPython.core.excolors import exception_colors
  86. from IPython.utils import PyColorize
  87. from IPython.utils import path as util_path
  88. from IPython.utils import py3compat
  89. from IPython.utils.terminal import get_terminal_size
  90. # Globals
  91. # amount of space to put line numbers before verbose tracebacks
  92. INDENT_SIZE = 8
  93. # Default color scheme. This is used, for example, by the traceback
  94. # formatter. When running in an actual IPython instance, the user's rc.colors
  95. # value is used, but having a module global makes this functionality available
  96. # to users of ultratb who are NOT running inside ipython.
  97. DEFAULT_SCHEME = 'NoColor'
  98. FAST_THRESHOLD = 10_000
  99. # ---------------------------------------------------------------------------
  100. # Code begins
  101. # Helper function -- largely belongs to VerboseTB, but we need the same
  102. # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
  103. # can be recognized properly by ipython.el's py-traceback-line-re
  104. # (SyntaxErrors have to be treated specially because they have no traceback)
  105. @functools.lru_cache()
  106. def count_lines_in_py_file(filename: str) -> int:
  107. """
  108. Given a filename, returns the number of lines in the file
  109. if it ends with the extension ".py". Otherwise, returns 0.
  110. """
  111. if not filename.endswith(".py"):
  112. return 0
  113. else:
  114. try:
  115. with open(filename, "r") as file:
  116. s = sum(1 for line in file)
  117. except UnicodeError:
  118. return 0
  119. return s
  120. """
  121. Given a frame object, returns the total number of lines in the file
  122. if the filename ends with the extension ".py". Otherwise, returns 0.
  123. """
  124. def get_line_number_of_frame(frame: types.FrameType) -> int:
  125. """
  126. Given a frame object, returns the total number of lines in the file
  127. containing the frame's code object, or the number of lines in the
  128. frame's source code if the file is not available.
  129. Parameters
  130. ----------
  131. frame : FrameType
  132. The frame object whose line number is to be determined.
  133. Returns
  134. -------
  135. int
  136. The total number of lines in the file containing the frame's
  137. code object, or the number of lines in the frame's source code
  138. if the file is not available.
  139. """
  140. filename = frame.f_code.co_filename
  141. if filename is None:
  142. print("No file....")
  143. lines, first = inspect.getsourcelines(frame)
  144. return first + len(lines)
  145. return count_lines_in_py_file(filename)
  146. def _safe_string(value, what, func=str):
  147. # Copied from cpython/Lib/traceback.py
  148. try:
  149. return func(value)
  150. except:
  151. return f"<{what} {func.__name__}() failed>"
  152. def _format_traceback_lines(lines, Colors, has_colors: bool, lvals):
  153. """
  154. Format tracebacks lines with pointing arrow, leading numbers...
  155. Parameters
  156. ----------
  157. lines : list[Line]
  158. Colors
  159. ColorScheme used.
  160. lvals : str
  161. Values of local variables, already colored, to inject just after the error line.
  162. """
  163. numbers_width = INDENT_SIZE - 1
  164. res = []
  165. for stack_line in lines:
  166. if stack_line is stack_data.LINE_GAP:
  167. res.append('%s (...)%s\n' % (Colors.linenoEm, Colors.Normal))
  168. continue
  169. line = stack_line.render(pygmented=has_colors).rstrip('\n') + '\n'
  170. lineno = stack_line.lineno
  171. if stack_line.is_current:
  172. # This is the line with the error
  173. pad = numbers_width - len(str(lineno))
  174. num = '%s%s' % (debugger.make_arrow(pad), str(lineno))
  175. start_color = Colors.linenoEm
  176. else:
  177. num = '%*s' % (numbers_width, lineno)
  178. start_color = Colors.lineno
  179. line = '%s%s%s %s' % (start_color, num, Colors.Normal, line)
  180. res.append(line)
  181. if lvals and stack_line.is_current:
  182. res.append(lvals + '\n')
  183. return res
  184. def _simple_format_traceback_lines(lnum, index, lines, Colors, lvals, _line_format):
  185. """
  186. Format tracebacks lines with pointing arrow, leading numbers...
  187. Parameters
  188. ==========
  189. lnum: int
  190. number of the target line of code.
  191. index: int
  192. which line in the list should be highlighted.
  193. lines: list[string]
  194. Colors:
  195. ColorScheme used.
  196. lvals: bytes
  197. Values of local variables, already colored, to inject just after the error line.
  198. _line_format: f (str) -> (str, bool)
  199. return (colorized version of str, failure to do so)
  200. """
  201. numbers_width = INDENT_SIZE - 1
  202. res = []
  203. for i, line in enumerate(lines, lnum - index):
  204. # assert isinstance(line, str)
  205. line = py3compat.cast_unicode(line)
  206. new_line, err = _line_format(line, "str")
  207. if not err:
  208. line = new_line
  209. if i == lnum:
  210. # This is the line with the error
  211. pad = numbers_width - len(str(i))
  212. num = "%s%s" % (debugger.make_arrow(pad), str(lnum))
  213. line = "%s%s%s %s%s" % (
  214. Colors.linenoEm,
  215. num,
  216. Colors.line,
  217. line,
  218. Colors.Normal,
  219. )
  220. else:
  221. num = "%*s" % (numbers_width, i)
  222. line = "%s%s%s %s" % (Colors.lineno, num, Colors.Normal, line)
  223. res.append(line)
  224. if lvals and i == lnum:
  225. res.append(lvals + "\n")
  226. return res
  227. def _format_filename(file, ColorFilename, ColorNormal, *, lineno=None):
  228. """
  229. Format filename lines with custom formatting from caching compiler or `File *.py` by default
  230. Parameters
  231. ----------
  232. file : str
  233. ColorFilename
  234. ColorScheme's filename coloring to be used.
  235. ColorNormal
  236. ColorScheme's normal coloring to be used.
  237. """
  238. ipinst = get_ipython()
  239. if (
  240. ipinst is not None
  241. and (data := ipinst.compile.format_code_name(file)) is not None
  242. ):
  243. label, name = data
  244. if lineno is None:
  245. tpl_link = f"{{label}} {ColorFilename}{{name}}{ColorNormal}"
  246. else:
  247. tpl_link = (
  248. f"{{label}} {ColorFilename}{{name}}, line {{lineno}}{ColorNormal}"
  249. )
  250. else:
  251. label = "File"
  252. name = util_path.compress_user(
  253. py3compat.cast_unicode(file, util_path.fs_encoding)
  254. )
  255. if lineno is None:
  256. tpl_link = f"{{label}} {ColorFilename}{{name}}{ColorNormal}"
  257. else:
  258. # can we make this the more friendly ", line {{lineno}}", or do we need to preserve the formatting with the colon?
  259. tpl_link = f"{{label}} {ColorFilename}{{name}}:{{lineno}}{ColorNormal}"
  260. return tpl_link.format(label=label, name=name, lineno=lineno)
  261. #---------------------------------------------------------------------------
  262. # Module classes
  263. class TBTools(colorable.Colorable):
  264. """Basic tools used by all traceback printer classes."""
  265. # Number of frames to skip when reporting tracebacks
  266. tb_offset = 0
  267. def __init__(
  268. self,
  269. color_scheme="NoColor",
  270. call_pdb=False,
  271. ostream=None,
  272. parent=None,
  273. config=None,
  274. *,
  275. debugger_cls=None,
  276. ):
  277. # Whether to call the interactive pdb debugger after printing
  278. # tracebacks or not
  279. super(TBTools, self).__init__(parent=parent, config=config)
  280. self.call_pdb = call_pdb
  281. # Output stream to write to. Note that we store the original value in
  282. # a private attribute and then make the public ostream a property, so
  283. # that we can delay accessing sys.stdout until runtime. The way
  284. # things are written now, the sys.stdout object is dynamically managed
  285. # so a reference to it should NEVER be stored statically. This
  286. # property approach confines this detail to a single location, and all
  287. # subclasses can simply access self.ostream for writing.
  288. self._ostream = ostream
  289. # Create color table
  290. self.color_scheme_table = exception_colors()
  291. self.set_colors(color_scheme)
  292. self.old_scheme = color_scheme # save initial value for toggles
  293. self.debugger_cls = debugger_cls or debugger.Pdb
  294. if call_pdb:
  295. self.pdb = self.debugger_cls()
  296. else:
  297. self.pdb = None
  298. def _get_ostream(self):
  299. """Output stream that exceptions are written to.
  300. Valid values are:
  301. - None: the default, which means that IPython will dynamically resolve
  302. to sys.stdout. This ensures compatibility with most tools, including
  303. Windows (where plain stdout doesn't recognize ANSI escapes).
  304. - Any object with 'write' and 'flush' attributes.
  305. """
  306. return sys.stdout if self._ostream is None else self._ostream
  307. def _set_ostream(self, val):
  308. assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
  309. self._ostream = val
  310. ostream = property(_get_ostream, _set_ostream)
  311. @staticmethod
  312. def _get_chained_exception(exception_value):
  313. cause = getattr(exception_value, "__cause__", None)
  314. if cause:
  315. return cause
  316. if getattr(exception_value, "__suppress_context__", False):
  317. return None
  318. return getattr(exception_value, "__context__", None)
  319. def get_parts_of_chained_exception(
  320. self, evalue
  321. ) -> Optional[Tuple[type, BaseException, TracebackType]]:
  322. chained_evalue = self._get_chained_exception(evalue)
  323. if chained_evalue:
  324. return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
  325. return None
  326. def prepare_chained_exception_message(self, cause) -> List[Any]:
  327. direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
  328. exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
  329. if cause:
  330. message = [[direct_cause]]
  331. else:
  332. message = [[exception_during_handling]]
  333. return message
  334. @property
  335. def has_colors(self) -> bool:
  336. return self.color_scheme_table.active_scheme_name.lower() != "nocolor"
  337. def set_colors(self, *args, **kw):
  338. """Shorthand access to the color table scheme selector method."""
  339. # Set own color table
  340. self.color_scheme_table.set_active_scheme(*args, **kw)
  341. # for convenience, set Colors to the active scheme
  342. self.Colors = self.color_scheme_table.active_colors
  343. # Also set colors of debugger
  344. if hasattr(self, 'pdb') and self.pdb is not None:
  345. self.pdb.set_colors(*args, **kw)
  346. def color_toggle(self):
  347. """Toggle between the currently active color scheme and NoColor."""
  348. if self.color_scheme_table.active_scheme_name == 'NoColor':
  349. self.color_scheme_table.set_active_scheme(self.old_scheme)
  350. self.Colors = self.color_scheme_table.active_colors
  351. else:
  352. self.old_scheme = self.color_scheme_table.active_scheme_name
  353. self.color_scheme_table.set_active_scheme('NoColor')
  354. self.Colors = self.color_scheme_table.active_colors
  355. def stb2text(self, stb):
  356. """Convert a structured traceback (a list) to a string."""
  357. return '\n'.join(stb)
  358. def text(self, etype, value, tb, tb_offset: Optional[int] = None, context=5):
  359. """Return formatted traceback.
  360. Subclasses may override this if they add extra arguments.
  361. """
  362. tb_list = self.structured_traceback(etype, value, tb,
  363. tb_offset, context)
  364. return self.stb2text(tb_list)
  365. def structured_traceback(
  366. self,
  367. etype: type,
  368. evalue: Optional[BaseException],
  369. etb: Optional[TracebackType] = None,
  370. tb_offset: Optional[int] = None,
  371. number_of_lines_of_context: int = 5,
  372. ):
  373. """Return a list of traceback frames.
  374. Must be implemented by each class.
  375. """
  376. raise NotImplementedError()
  377. #---------------------------------------------------------------------------
  378. class ListTB(TBTools):
  379. """Print traceback information from a traceback list, with optional color.
  380. Calling requires 3 arguments: (etype, evalue, elist)
  381. as would be obtained by::
  382. etype, evalue, tb = sys.exc_info()
  383. if tb:
  384. elist = traceback.extract_tb(tb)
  385. else:
  386. elist = None
  387. It can thus be used by programs which need to process the traceback before
  388. printing (such as console replacements based on the code module from the
  389. standard library).
  390. Because they are meant to be called without a full traceback (only a
  391. list), instances of this class can't call the interactive pdb debugger."""
  392. def __call__(self, etype, value, elist):
  393. self.ostream.flush()
  394. self.ostream.write(self.text(etype, value, elist))
  395. self.ostream.write('\n')
  396. def _extract_tb(self, tb):
  397. if tb:
  398. return traceback.extract_tb(tb)
  399. else:
  400. return None
  401. def structured_traceback(
  402. self,
  403. etype: type,
  404. evalue: Optional[BaseException],
  405. etb: Optional[TracebackType] = None,
  406. tb_offset: Optional[int] = None,
  407. context=5,
  408. ):
  409. """Return a color formatted string with the traceback info.
  410. Parameters
  411. ----------
  412. etype : exception type
  413. Type of the exception raised.
  414. evalue : object
  415. Data stored in the exception
  416. etb : list | TracebackType | None
  417. If list: List of frames, see class docstring for details.
  418. If Traceback: Traceback of the exception.
  419. tb_offset : int, optional
  420. Number of frames in the traceback to skip. If not given, the
  421. instance evalue is used (set in constructor).
  422. context : int, optional
  423. Number of lines of context information to print.
  424. Returns
  425. -------
  426. String with formatted exception.
  427. """
  428. # This is a workaround to get chained_exc_ids in recursive calls
  429. # etb should not be a tuple if structured_traceback is not recursive
  430. if isinstance(etb, tuple):
  431. etb, chained_exc_ids = etb
  432. else:
  433. chained_exc_ids = set()
  434. if isinstance(etb, list):
  435. elist = etb
  436. elif etb is not None:
  437. elist = self._extract_tb(etb)
  438. else:
  439. elist = []
  440. tb_offset = self.tb_offset if tb_offset is None else tb_offset
  441. assert isinstance(tb_offset, int)
  442. Colors = self.Colors
  443. out_list = []
  444. if elist:
  445. if tb_offset and len(elist) > tb_offset:
  446. elist = elist[tb_offset:]
  447. out_list.append('Traceback %s(most recent call last)%s:' %
  448. (Colors.normalEm, Colors.Normal) + '\n')
  449. out_list.extend(self._format_list(elist))
  450. # The exception info should be a single entry in the list.
  451. lines = ''.join(self._format_exception_only(etype, evalue))
  452. out_list.append(lines)
  453. exception = self.get_parts_of_chained_exception(evalue)
  454. if exception and (id(exception[1]) not in chained_exc_ids):
  455. chained_exception_message = (
  456. self.prepare_chained_exception_message(evalue.__cause__)[0]
  457. if evalue is not None
  458. else ""
  459. )
  460. etype, evalue, etb = exception
  461. # Trace exception to avoid infinite 'cause' loop
  462. chained_exc_ids.add(id(exception[1]))
  463. chained_exceptions_tb_offset = 0
  464. out_list = (
  465. self.structured_traceback(
  466. etype,
  467. evalue,
  468. (etb, chained_exc_ids), # type: ignore
  469. chained_exceptions_tb_offset,
  470. context,
  471. )
  472. + chained_exception_message
  473. + out_list)
  474. return out_list
  475. def _format_list(self, extracted_list):
  476. """Format a list of traceback entry tuples for printing.
  477. Given a list of tuples as returned by extract_tb() or
  478. extract_stack(), return a list of strings ready for printing.
  479. Each string in the resulting list corresponds to the item with the
  480. same index in the argument list. Each string ends in a newline;
  481. the strings may contain internal newlines as well, for those items
  482. whose source text line is not None.
  483. Lifted almost verbatim from traceback.py
  484. """
  485. Colors = self.Colors
  486. output_list = []
  487. for ind, (filename, lineno, name, line) in enumerate(extracted_list):
  488. normalCol, nameCol, fileCol, lineCol = (
  489. # Emphasize the last entry
  490. (Colors.normalEm, Colors.nameEm, Colors.filenameEm, Colors.line)
  491. if ind == len(extracted_list) - 1
  492. else (Colors.Normal, Colors.name, Colors.filename, "")
  493. )
  494. fns = _format_filename(filename, fileCol, normalCol, lineno=lineno)
  495. item = f"{normalCol} {fns}"
  496. if name != "<module>":
  497. item += f" in {nameCol}{name}{normalCol}\n"
  498. else:
  499. item += "\n"
  500. if line:
  501. item += f"{lineCol} {line.strip()}{normalCol}\n"
  502. output_list.append(item)
  503. return output_list
  504. def _format_exception_only(self, etype, value):
  505. """Format the exception part of a traceback.
  506. The arguments are the exception type and value such as given by
  507. sys.exc_info()[:2]. The return value is a list of strings, each ending
  508. in a newline. Normally, the list contains a single string; however,
  509. for SyntaxError exceptions, it contains several lines that (when
  510. printed) display detailed information about where the syntax error
  511. occurred. The message indicating which exception occurred is the
  512. always last string in the list.
  513. Also lifted nearly verbatim from traceback.py
  514. """
  515. have_filedata = False
  516. Colors = self.Colors
  517. output_list = []
  518. stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
  519. if value is None:
  520. # Not sure if this can still happen in Python 2.6 and above
  521. output_list.append(stype + "\n")
  522. else:
  523. if issubclass(etype, SyntaxError):
  524. have_filedata = True
  525. if not value.filename: value.filename = "<string>"
  526. if value.lineno:
  527. lineno = value.lineno
  528. textline = linecache.getline(value.filename, value.lineno)
  529. else:
  530. lineno = "unknown"
  531. textline = ""
  532. output_list.append(
  533. "%s %s%s\n"
  534. % (
  535. Colors.normalEm,
  536. _format_filename(
  537. value.filename,
  538. Colors.filenameEm,
  539. Colors.normalEm,
  540. lineno=(None if lineno == "unknown" else lineno),
  541. ),
  542. Colors.Normal,
  543. )
  544. )
  545. if textline == "":
  546. textline = py3compat.cast_unicode(value.text, "utf-8")
  547. if textline is not None:
  548. i = 0
  549. while i < len(textline) and textline[i].isspace():
  550. i += 1
  551. output_list.append(
  552. "%s %s%s\n" % (Colors.line, textline.strip(), Colors.Normal)
  553. )
  554. if value.offset is not None:
  555. s = ' '
  556. for c in textline[i:value.offset - 1]:
  557. if c.isspace():
  558. s += c
  559. else:
  560. s += " "
  561. output_list.append(
  562. "%s%s^%s\n" % (Colors.caret, s, Colors.Normal)
  563. )
  564. try:
  565. s = value.msg
  566. except Exception:
  567. s = self._some_str(value)
  568. if s:
  569. output_list.append(
  570. "%s%s:%s %s\n" % (stype, Colors.excName, Colors.Normal, s)
  571. )
  572. else:
  573. output_list.append("%s\n" % stype)
  574. # PEP-678 notes
  575. output_list.extend(f"{x}\n" for x in getattr(value, "__notes__", []))
  576. # sync with user hooks
  577. if have_filedata:
  578. ipinst = get_ipython()
  579. if ipinst is not None:
  580. ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
  581. return output_list
  582. def get_exception_only(self, etype, value):
  583. """Only print the exception type and message, without a traceback.
  584. Parameters
  585. ----------
  586. etype : exception type
  587. value : exception value
  588. """
  589. return ListTB.structured_traceback(self, etype, value)
  590. def show_exception_only(self, etype, evalue):
  591. """Only print the exception type and message, without a traceback.
  592. Parameters
  593. ----------
  594. etype : exception type
  595. evalue : exception value
  596. """
  597. # This method needs to use __call__ from *this* class, not the one from
  598. # a subclass whose signature or behavior may be different
  599. ostream = self.ostream
  600. ostream.flush()
  601. ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
  602. ostream.flush()
  603. def _some_str(self, value):
  604. # Lifted from traceback.py
  605. try:
  606. return py3compat.cast_unicode(str(value))
  607. except:
  608. return u'<unprintable %s object>' % type(value).__name__
  609. class FrameInfo:
  610. """
  611. Mirror of stack data's FrameInfo, but so that we can bypass highlighting on
  612. really long frames.
  613. """
  614. description: Optional[str]
  615. filename: Optional[str]
  616. lineno: Tuple[int]
  617. # number of context lines to use
  618. context: Optional[int]
  619. @classmethod
  620. def _from_stack_data_FrameInfo(cls, frame_info):
  621. return cls(
  622. getattr(frame_info, "description", None),
  623. getattr(frame_info, "filename", None), # type: ignore[arg-type]
  624. getattr(frame_info, "lineno", None), # type: ignore[arg-type]
  625. getattr(frame_info, "frame", None),
  626. getattr(frame_info, "code", None),
  627. sd=frame_info,
  628. context=None,
  629. )
  630. def __init__(
  631. self,
  632. description: Optional[str],
  633. filename: str,
  634. lineno: Tuple[int],
  635. frame,
  636. code,
  637. *,
  638. sd=None,
  639. context=None,
  640. ):
  641. self.description = description
  642. self.filename = filename
  643. self.lineno = lineno
  644. self.frame = frame
  645. self.code = code
  646. self._sd = sd
  647. self.context = context
  648. # self.lines = []
  649. if sd is None:
  650. ix = inspect.getsourcelines(frame)
  651. self.raw_lines = ix[0]
  652. @property
  653. def variables_in_executing_piece(self):
  654. if self._sd:
  655. return self._sd.variables_in_executing_piece
  656. else:
  657. return []
  658. @property
  659. def lines(self):
  660. return self._sd.lines
  661. @property
  662. def executing(self):
  663. if self._sd:
  664. return self._sd.executing
  665. else:
  666. return None
  667. # ----------------------------------------------------------------------------
  668. class VerboseTB(TBTools):
  669. """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
  670. of HTML. Requires inspect and pydoc. Crazy, man.
  671. Modified version which optionally strips the topmost entries from the
  672. traceback, to be used with alternate interpreters (because their own code
  673. would appear in the traceback)."""
  674. _tb_highlight = ""
  675. _tb_highlight_style = "default"
  676. def __init__(
  677. self,
  678. color_scheme: str = "Linux",
  679. call_pdb: bool = False,
  680. ostream=None,
  681. tb_offset: int = 0,
  682. long_header: bool = False,
  683. include_vars: bool = True,
  684. check_cache=None,
  685. debugger_cls=None,
  686. parent=None,
  687. config=None,
  688. ):
  689. """Specify traceback offset, headers and color scheme.
  690. Define how many frames to drop from the tracebacks. Calling it with
  691. tb_offset=1 allows use of this handler in interpreters which will have
  692. their own code at the top of the traceback (VerboseTB will first
  693. remove that frame before printing the traceback info)."""
  694. TBTools.__init__(
  695. self,
  696. color_scheme=color_scheme,
  697. call_pdb=call_pdb,
  698. ostream=ostream,
  699. parent=parent,
  700. config=config,
  701. debugger_cls=debugger_cls,
  702. )
  703. self.tb_offset = tb_offset
  704. self.long_header = long_header
  705. self.include_vars = include_vars
  706. # By default we use linecache.checkcache, but the user can provide a
  707. # different check_cache implementation. This was formerly used by the
  708. # IPython kernel for interactive code, but is no longer necessary.
  709. if check_cache is None:
  710. check_cache = linecache.checkcache
  711. self.check_cache = check_cache
  712. self.skip_hidden = True
  713. def format_record(self, frame_info: FrameInfo):
  714. """Format a single stack frame"""
  715. assert isinstance(frame_info, FrameInfo)
  716. Colors = self.Colors # just a shorthand + quicker name lookup
  717. ColorsNormal = Colors.Normal # used a lot
  718. if isinstance(frame_info._sd, stack_data.RepeatedFrames):
  719. return ' %s[... skipping similar frames: %s]%s\n' % (
  720. Colors.excName, frame_info.description, ColorsNormal)
  721. indent = " " * INDENT_SIZE
  722. em_normal = "%s\n%s%s" % (Colors.valEm, indent, ColorsNormal)
  723. tpl_call = f"in {Colors.vName}{{file}}{Colors.valEm}{{scope}}{ColorsNormal}"
  724. tpl_call_fail = "in %s%%s%s(***failed resolving arguments***)%s" % (
  725. Colors.vName,
  726. Colors.valEm,
  727. ColorsNormal,
  728. )
  729. tpl_name_val = "%%s %s= %%s%s" % (Colors.valEm, ColorsNormal)
  730. link = _format_filename(
  731. frame_info.filename,
  732. Colors.filenameEm,
  733. ColorsNormal,
  734. lineno=frame_info.lineno,
  735. )
  736. args, varargs, varkw, locals_ = inspect.getargvalues(frame_info.frame)
  737. if frame_info.executing is not None:
  738. func = frame_info.executing.code_qualname()
  739. else:
  740. func = "?"
  741. if func == "<module>":
  742. call = ""
  743. else:
  744. # Decide whether to include variable details or not
  745. var_repr = eqrepr if self.include_vars else nullrepr
  746. try:
  747. scope = inspect.formatargvalues(
  748. args, varargs, varkw, locals_, formatvalue=var_repr
  749. )
  750. call = tpl_call.format(file=func, scope=scope)
  751. except KeyError:
  752. # This happens in situations like errors inside generator
  753. # expressions, where local variables are listed in the
  754. # line, but can't be extracted from the frame. I'm not
  755. # 100% sure this isn't actually a bug in inspect itself,
  756. # but since there's no info for us to compute with, the
  757. # best we can do is report the failure and move on. Here
  758. # we must *not* call any traceback construction again,
  759. # because that would mess up use of %debug later on. So we
  760. # simply report the failure and move on. The only
  761. # limitation will be that this frame won't have locals
  762. # listed in the call signature. Quite subtle problem...
  763. # I can't think of a good way to validate this in a unit
  764. # test, but running a script consisting of:
  765. # dict( (k,v.strip()) for (k,v) in range(10) )
  766. # will illustrate the error, if this exception catch is
  767. # disabled.
  768. call = tpl_call_fail % func
  769. lvals = ''
  770. lvals_list = []
  771. if self.include_vars:
  772. try:
  773. # we likely want to fix stackdata at some point, but
  774. # still need a workaround.
  775. fibp = frame_info.variables_in_executing_piece
  776. for var in fibp:
  777. lvals_list.append(tpl_name_val % (var.name, repr(var.value)))
  778. except Exception:
  779. lvals_list.append(
  780. "Exception trying to inspect frame. No more locals available."
  781. )
  782. if lvals_list:
  783. lvals = '%s%s' % (indent, em_normal.join(lvals_list))
  784. result = f'{link}{", " if call else ""}{call}\n'
  785. if frame_info._sd is None:
  786. # fast fallback if file is too long
  787. tpl_link = "%s%%s%s" % (Colors.filenameEm, ColorsNormal)
  788. link = tpl_link % util_path.compress_user(frame_info.filename)
  789. level = "%s %s\n" % (link, call)
  790. _line_format = PyColorize.Parser(
  791. style=self.color_scheme_table.active_scheme_name, parent=self
  792. ).format2
  793. first_line = frame_info.code.co_firstlineno
  794. current_line = frame_info.lineno[0]
  795. raw_lines = frame_info.raw_lines
  796. index = current_line - first_line
  797. if index >= frame_info.context:
  798. start = max(index - frame_info.context, 0)
  799. stop = index + frame_info.context
  800. index = frame_info.context
  801. else:
  802. start = 0
  803. stop = index + frame_info.context
  804. raw_lines = raw_lines[start:stop]
  805. return "%s%s" % (
  806. level,
  807. "".join(
  808. _simple_format_traceback_lines(
  809. current_line,
  810. index,
  811. raw_lines,
  812. Colors,
  813. lvals,
  814. _line_format,
  815. )
  816. ),
  817. )
  818. # result += "\n".join(frame_info.raw_lines)
  819. else:
  820. result += "".join(
  821. _format_traceback_lines(
  822. frame_info.lines, Colors, self.has_colors, lvals
  823. )
  824. )
  825. return result
  826. def prepare_header(self, etype: str, long_version: bool = False):
  827. colors = self.Colors # just a shorthand + quicker name lookup
  828. colorsnormal = colors.Normal # used a lot
  829. exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
  830. width = min(75, get_terminal_size()[0])
  831. if long_version:
  832. # Header with the exception type, python version, and date
  833. pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
  834. date = time.ctime(time.time())
  835. head = "%s%s%s\n%s%s%s\n%s" % (
  836. colors.topline,
  837. "-" * width,
  838. colorsnormal,
  839. exc,
  840. " " * (width - len(etype) - len(pyver)),
  841. pyver,
  842. date.rjust(width),
  843. )
  844. head += (
  845. "\nA problem occurred executing Python code. Here is the sequence of function"
  846. "\ncalls leading up to the error, with the most recent (innermost) call last."
  847. )
  848. else:
  849. # Simplified header
  850. head = "%s%s" % (
  851. exc,
  852. "Traceback (most recent call last)".rjust(width - len(etype)),
  853. )
  854. return head
  855. def format_exception(self, etype, evalue):
  856. colors = self.Colors # just a shorthand + quicker name lookup
  857. colorsnormal = colors.Normal # used a lot
  858. # Get (safely) a string form of the exception info
  859. try:
  860. etype_str, evalue_str = map(str, (etype, evalue))
  861. except:
  862. # User exception is improperly defined.
  863. etype, evalue = str, sys.exc_info()[:2]
  864. etype_str, evalue_str = map(str, (etype, evalue))
  865. # PEP-678 notes
  866. notes = getattr(evalue, "__notes__", [])
  867. if not isinstance(notes, Sequence) or isinstance(notes, (str, bytes)):
  868. notes = [_safe_string(notes, "__notes__", func=repr)]
  869. # ... and format it
  870. return [
  871. "{}{}{}: {}".format(
  872. colors.excName,
  873. etype_str,
  874. colorsnormal,
  875. py3compat.cast_unicode(evalue_str),
  876. ),
  877. *(
  878. "{}{}".format(
  879. colorsnormal, _safe_string(py3compat.cast_unicode(n), "note")
  880. )
  881. for n in notes
  882. ),
  883. ]
  884. def format_exception_as_a_whole(
  885. self,
  886. etype: type,
  887. evalue: Optional[BaseException],
  888. etb: Optional[TracebackType],
  889. number_of_lines_of_context,
  890. tb_offset: Optional[int],
  891. ):
  892. """Formats the header, traceback and exception message for a single exception.
  893. This may be called multiple times by Python 3 exception chaining
  894. (PEP 3134).
  895. """
  896. # some locals
  897. orig_etype = etype
  898. try:
  899. etype = etype.__name__ # type: ignore
  900. except AttributeError:
  901. pass
  902. tb_offset = self.tb_offset if tb_offset is None else tb_offset
  903. assert isinstance(tb_offset, int)
  904. head = self.prepare_header(str(etype), self.long_header)
  905. records = (
  906. self.get_records(etb, number_of_lines_of_context, tb_offset) if etb else []
  907. )
  908. frames = []
  909. skipped = 0
  910. lastrecord = len(records) - 1
  911. for i, record in enumerate(records):
  912. if (
  913. not isinstance(record._sd, stack_data.RepeatedFrames)
  914. and self.skip_hidden
  915. ):
  916. if (
  917. record.frame.f_locals.get("__tracebackhide__", 0)
  918. and i != lastrecord
  919. ):
  920. skipped += 1
  921. continue
  922. if skipped:
  923. Colors = self.Colors # just a shorthand + quicker name lookup
  924. ColorsNormal = Colors.Normal # used a lot
  925. frames.append(
  926. " %s[... skipping hidden %s frame]%s\n"
  927. % (Colors.excName, skipped, ColorsNormal)
  928. )
  929. skipped = 0
  930. frames.append(self.format_record(record))
  931. if skipped:
  932. Colors = self.Colors # just a shorthand + quicker name lookup
  933. ColorsNormal = Colors.Normal # used a lot
  934. frames.append(
  935. " %s[... skipping hidden %s frame]%s\n"
  936. % (Colors.excName, skipped, ColorsNormal)
  937. )
  938. formatted_exception = self.format_exception(etype, evalue)
  939. if records:
  940. frame_info = records[-1]
  941. ipinst = get_ipython()
  942. if ipinst is not None:
  943. ipinst.hooks.synchronize_with_editor(frame_info.filename, frame_info.lineno, 0)
  944. return [[head] + frames + formatted_exception]
  945. def get_records(
  946. self, etb: TracebackType, number_of_lines_of_context: int, tb_offset: int
  947. ):
  948. assert etb is not None
  949. context = number_of_lines_of_context - 1
  950. after = context // 2
  951. before = context - after
  952. if self.has_colors:
  953. style = get_style_by_name(self._tb_highlight_style)
  954. style = stack_data.style_with_executing_node(style, self._tb_highlight)
  955. formatter = Terminal256Formatter(style=style)
  956. else:
  957. formatter = None
  958. options = stack_data.Options(
  959. before=before,
  960. after=after,
  961. pygments_formatter=formatter,
  962. )
  963. # Let's estimate the amount of code we will have to parse/highlight.
  964. cf: Optional[TracebackType] = etb
  965. max_len = 0
  966. tbs = []
  967. while cf is not None:
  968. try:
  969. mod = inspect.getmodule(cf.tb_frame)
  970. if mod is not None:
  971. mod_name = mod.__name__
  972. root_name, *_ = mod_name.split(".")
  973. if root_name == "IPython":
  974. cf = cf.tb_next
  975. continue
  976. max_len = get_line_number_of_frame(cf.tb_frame)
  977. except OSError:
  978. max_len = 0
  979. max_len = max(max_len, max_len)
  980. tbs.append(cf)
  981. cf = getattr(cf, "tb_next", None)
  982. if max_len > FAST_THRESHOLD:
  983. FIs = []
  984. for tb in tbs:
  985. frame = tb.tb_frame # type: ignore
  986. lineno = (frame.f_lineno,)
  987. code = frame.f_code
  988. filename = code.co_filename
  989. # TODO: Here we need to use before/after/
  990. FIs.append(
  991. FrameInfo(
  992. "Raw frame", filename, lineno, frame, code, context=context
  993. )
  994. )
  995. return FIs
  996. res = list(stack_data.FrameInfo.stack_data(etb, options=options))[tb_offset:]
  997. res = [FrameInfo._from_stack_data_FrameInfo(r) for r in res]
  998. return res
  999. def structured_traceback(
  1000. self,
  1001. etype: type,
  1002. evalue: Optional[BaseException],
  1003. etb: Optional[TracebackType] = None,
  1004. tb_offset: Optional[int] = None,
  1005. number_of_lines_of_context: int = 5,
  1006. ):
  1007. """Return a nice text document describing the traceback."""
  1008. formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
  1009. tb_offset)
  1010. colors = self.Colors # just a shorthand + quicker name lookup
  1011. colorsnormal = colors.Normal # used a lot
  1012. head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
  1013. structured_traceback_parts = [head]
  1014. chained_exceptions_tb_offset = 0
  1015. lines_of_context = 3
  1016. formatted_exceptions = formatted_exception
  1017. exception = self.get_parts_of_chained_exception(evalue)
  1018. if exception:
  1019. assert evalue is not None
  1020. formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
  1021. etype, evalue, etb = exception
  1022. else:
  1023. evalue = None
  1024. chained_exc_ids = set()
  1025. while evalue:
  1026. formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
  1027. chained_exceptions_tb_offset)
  1028. exception = self.get_parts_of_chained_exception(evalue)
  1029. if exception and not id(exception[1]) in chained_exc_ids:
  1030. chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
  1031. formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
  1032. etype, evalue, etb = exception
  1033. else:
  1034. evalue = None
  1035. # we want to see exceptions in a reversed order:
  1036. # the first exception should be on top
  1037. for formatted_exception in reversed(formatted_exceptions):
  1038. structured_traceback_parts += formatted_exception
  1039. return structured_traceback_parts
  1040. def debugger(self, force: bool = False):
  1041. """Call up the pdb debugger if desired, always clean up the tb
  1042. reference.
  1043. Keywords:
  1044. - force(False): by default, this routine checks the instance call_pdb
  1045. flag and does not actually invoke the debugger if the flag is false.
  1046. The 'force' option forces the debugger to activate even if the flag
  1047. is false.
  1048. If the call_pdb flag is set, the pdb interactive debugger is
  1049. invoked. In all cases, the self.tb reference to the current traceback
  1050. is deleted to prevent lingering references which hamper memory
  1051. management.
  1052. Note that each call to pdb() does an 'import readline', so if your app
  1053. requires a special setup for the readline completers, you'll have to
  1054. fix that by hand after invoking the exception handler."""
  1055. if force or self.call_pdb:
  1056. if self.pdb is None:
  1057. self.pdb = self.debugger_cls()
  1058. # the system displayhook may have changed, restore the original
  1059. # for pdb
  1060. display_trap = DisplayTrap(hook=sys.__displayhook__)
  1061. with display_trap:
  1062. self.pdb.reset()
  1063. # Find the right frame so we don't pop up inside ipython itself
  1064. if hasattr(self, "tb") and self.tb is not None: # type: ignore[has-type]
  1065. etb = self.tb # type: ignore[has-type]
  1066. else:
  1067. etb = self.tb = sys.last_traceback
  1068. while self.tb is not None and self.tb.tb_next is not None:
  1069. assert self.tb.tb_next is not None
  1070. self.tb = self.tb.tb_next
  1071. if etb and etb.tb_next:
  1072. etb = etb.tb_next
  1073. self.pdb.botframe = etb.tb_frame
  1074. # last_value should be deprecated, but last-exc sometimme not set
  1075. # please check why later and remove the getattr.
  1076. exc = sys.last_value if sys.version_info < (3, 12) else getattr(sys, "last_exc", sys.last_value) # type: ignore[attr-defined]
  1077. if exc:
  1078. self.pdb.interaction(None, exc)
  1079. else:
  1080. self.pdb.interaction(None, etb)
  1081. if hasattr(self, 'tb'):
  1082. del self.tb
  1083. def handler(self, info=None):
  1084. (etype, evalue, etb) = info or sys.exc_info()
  1085. self.tb = etb
  1086. ostream = self.ostream
  1087. ostream.flush()
  1088. ostream.write(self.text(etype, evalue, etb))
  1089. ostream.write('\n')
  1090. ostream.flush()
  1091. # Changed so an instance can just be called as VerboseTB_inst() and print
  1092. # out the right info on its own.
  1093. def __call__(self, etype=None, evalue=None, etb=None):
  1094. """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
  1095. if etb is None:
  1096. self.handler()
  1097. else:
  1098. self.handler((etype, evalue, etb))
  1099. try:
  1100. self.debugger()
  1101. except KeyboardInterrupt:
  1102. print("\nKeyboardInterrupt")
  1103. #----------------------------------------------------------------------------
  1104. class FormattedTB(VerboseTB, ListTB):
  1105. """Subclass ListTB but allow calling with a traceback.
  1106. It can thus be used as a sys.excepthook for Python > 2.1.
  1107. Also adds 'Context' and 'Verbose' modes, not available in ListTB.
  1108. Allows a tb_offset to be specified. This is useful for situations where
  1109. one needs to remove a number of topmost frames from the traceback (such as
  1110. occurs with python programs that themselves execute other python code,
  1111. like Python shells). """
  1112. mode: str
  1113. def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
  1114. ostream=None,
  1115. tb_offset=0, long_header=False, include_vars=False,
  1116. check_cache=None, debugger_cls=None,
  1117. parent=None, config=None):
  1118. # NEVER change the order of this list. Put new modes at the end:
  1119. self.valid_modes = ['Plain', 'Context', 'Verbose', 'Minimal']
  1120. self.verbose_modes = self.valid_modes[1:3]
  1121. VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
  1122. ostream=ostream, tb_offset=tb_offset,
  1123. long_header=long_header, include_vars=include_vars,
  1124. check_cache=check_cache, debugger_cls=debugger_cls,
  1125. parent=parent, config=config)
  1126. # Different types of tracebacks are joined with different separators to
  1127. # form a single string. They are taken from this dict
  1128. self._join_chars = dict(Plain='', Context='\n', Verbose='\n',
  1129. Minimal='')
  1130. # set_mode also sets the tb_join_char attribute
  1131. self.set_mode(mode)
  1132. def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
  1133. tb_offset = self.tb_offset if tb_offset is None else tb_offset
  1134. mode = self.mode
  1135. if mode in self.verbose_modes:
  1136. # Verbose modes need a full traceback
  1137. return VerboseTB.structured_traceback(
  1138. self, etype, value, tb, tb_offset, number_of_lines_of_context
  1139. )
  1140. elif mode == 'Minimal':
  1141. return ListTB.get_exception_only(self, etype, value)
  1142. else:
  1143. # We must check the source cache because otherwise we can print
  1144. # out-of-date source code.
  1145. self.check_cache()
  1146. # Now we can extract and format the exception
  1147. return ListTB.structured_traceback(
  1148. self, etype, value, tb, tb_offset, number_of_lines_of_context
  1149. )
  1150. def stb2text(self, stb):
  1151. """Convert a structured traceback (a list) to a string."""
  1152. return self.tb_join_char.join(stb)
  1153. def set_mode(self, mode: Optional[str] = None):
  1154. """Switch to the desired mode.
  1155. If mode is not specified, cycles through the available modes."""
  1156. if not mode:
  1157. new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
  1158. len(self.valid_modes)
  1159. self.mode = self.valid_modes[new_idx]
  1160. elif mode not in self.valid_modes:
  1161. raise ValueError(
  1162. "Unrecognized mode in FormattedTB: <" + mode + ">\n"
  1163. "Valid modes: " + str(self.valid_modes)
  1164. )
  1165. else:
  1166. assert isinstance(mode, str)
  1167. self.mode = mode
  1168. # include variable details only in 'Verbose' mode
  1169. self.include_vars = (self.mode == self.valid_modes[2])
  1170. # Set the join character for generating text tracebacks
  1171. self.tb_join_char = self._join_chars[self.mode]
  1172. # some convenient shortcuts
  1173. def plain(self):
  1174. self.set_mode(self.valid_modes[0])
  1175. def context(self):
  1176. self.set_mode(self.valid_modes[1])
  1177. def verbose(self):
  1178. self.set_mode(self.valid_modes[2])
  1179. def minimal(self):
  1180. self.set_mode(self.valid_modes[3])
  1181. #----------------------------------------------------------------------------
  1182. class AutoFormattedTB(FormattedTB):
  1183. """A traceback printer which can be called on the fly.
  1184. It will find out about exceptions by itself.
  1185. A brief example::
  1186. AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
  1187. try:
  1188. ...
  1189. except:
  1190. AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
  1191. """
  1192. def __call__(self, etype=None, evalue=None, etb=None,
  1193. out=None, tb_offset=None):
  1194. """Print out a formatted exception traceback.
  1195. Optional arguments:
  1196. - out: an open file-like object to direct output to.
  1197. - tb_offset: the number of frames to skip over in the stack, on a
  1198. per-call basis (this overrides temporarily the instance's tb_offset
  1199. given at initialization time."""
  1200. if out is None:
  1201. out = self.ostream
  1202. out.flush()
  1203. out.write(self.text(etype, evalue, etb, tb_offset))
  1204. out.write('\n')
  1205. out.flush()
  1206. # FIXME: we should remove the auto pdb behavior from here and leave
  1207. # that to the clients.
  1208. try:
  1209. self.debugger()
  1210. except KeyboardInterrupt:
  1211. print("\nKeyboardInterrupt")
  1212. def structured_traceback(
  1213. self,
  1214. etype: type,
  1215. evalue: Optional[BaseException],
  1216. etb: Optional[TracebackType] = None,
  1217. tb_offset: Optional[int] = None,
  1218. number_of_lines_of_context: int = 5,
  1219. ):
  1220. # tb: TracebackType or tupleof tb types ?
  1221. if etype is None:
  1222. etype, evalue, etb = sys.exc_info()
  1223. if isinstance(etb, tuple):
  1224. # tb is a tuple if this is a chained exception.
  1225. self.tb = etb[0]
  1226. else:
  1227. self.tb = etb
  1228. return FormattedTB.structured_traceback(
  1229. self, etype, evalue, etb, tb_offset, number_of_lines_of_context
  1230. )
  1231. #---------------------------------------------------------------------------
  1232. # A simple class to preserve Nathan's original functionality.
  1233. class ColorTB(FormattedTB):
  1234. """Shorthand to initialize a FormattedTB in Linux colors mode."""
  1235. def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
  1236. FormattedTB.__init__(self, color_scheme=color_scheme,
  1237. call_pdb=call_pdb, **kwargs)
  1238. class SyntaxTB(ListTB):
  1239. """Extension which holds some state: the last exception value"""
  1240. def __init__(self, color_scheme='NoColor', parent=None, config=None):
  1241. ListTB.__init__(self, color_scheme, parent=parent, config=config)
  1242. self.last_syntax_error = None
  1243. def __call__(self, etype, value, elist):
  1244. self.last_syntax_error = value
  1245. ListTB.__call__(self, etype, value, elist)
  1246. def structured_traceback(self, etype, value, elist, tb_offset=None,
  1247. context=5):
  1248. # If the source file has been edited, the line in the syntax error can
  1249. # be wrong (retrieved from an outdated cache). This replaces it with
  1250. # the current value.
  1251. if isinstance(value, SyntaxError) \
  1252. and isinstance(value.filename, str) \
  1253. and isinstance(value.lineno, int):
  1254. linecache.checkcache(value.filename)
  1255. newtext = linecache.getline(value.filename, value.lineno)
  1256. if newtext:
  1257. value.text = newtext
  1258. self.last_syntax_error = value
  1259. return super(SyntaxTB, self).structured_traceback(etype, value, elist,
  1260. tb_offset=tb_offset, context=context)
  1261. def clear_err_state(self):
  1262. """Return the current error state and clear it"""
  1263. e = self.last_syntax_error
  1264. self.last_syntax_error = None
  1265. return e
  1266. def stb2text(self, stb):
  1267. """Convert a structured traceback (a list) to a string."""
  1268. return ''.join(stb)
  1269. # some internal-use functions
  1270. def text_repr(value):
  1271. """Hopefully pretty robust repr equivalent."""
  1272. # this is pretty horrible but should always return *something*
  1273. try:
  1274. return pydoc.text.repr(value) # type: ignore[call-arg]
  1275. except KeyboardInterrupt:
  1276. raise
  1277. except:
  1278. try:
  1279. return repr(value)
  1280. except KeyboardInterrupt:
  1281. raise
  1282. except:
  1283. try:
  1284. # all still in an except block so we catch
  1285. # getattr raising
  1286. name = getattr(value, '__name__', None)
  1287. if name:
  1288. # ick, recursion
  1289. return text_repr(name)
  1290. klass = getattr(value, '__class__', None)
  1291. if klass:
  1292. return '%s instance' % text_repr(klass)
  1293. except KeyboardInterrupt:
  1294. raise
  1295. except:
  1296. return 'UNRECOVERABLE REPR FAILURE'
  1297. def eqrepr(value, repr=text_repr):
  1298. return '=%s' % repr(value)
  1299. def nullrepr(value, repr=text_repr):
  1300. return ''