ultratb.py 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547
  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. # Find chained exceptions if we have a traceback (not for exception-only mode)
  454. if etb is not None:
  455. exception = self.get_parts_of_chained_exception(evalue)
  456. if exception and (id(exception[1]) not in chained_exc_ids):
  457. chained_exception_message = (
  458. self.prepare_chained_exception_message(evalue.__cause__)[0]
  459. if evalue is not None
  460. else ""
  461. )
  462. etype, evalue, etb = exception
  463. # Trace exception to avoid infinite 'cause' loop
  464. chained_exc_ids.add(id(exception[1]))
  465. chained_exceptions_tb_offset = 0
  466. out_list = (
  467. self.structured_traceback(
  468. etype,
  469. evalue,
  470. (etb, chained_exc_ids), # type: ignore
  471. chained_exceptions_tb_offset,
  472. context,
  473. )
  474. + chained_exception_message
  475. + out_list
  476. )
  477. return out_list
  478. def _format_list(self, extracted_list):
  479. """Format a list of traceback entry tuples for printing.
  480. Given a list of tuples as returned by extract_tb() or
  481. extract_stack(), return a list of strings ready for printing.
  482. Each string in the resulting list corresponds to the item with the
  483. same index in the argument list. Each string ends in a newline;
  484. the strings may contain internal newlines as well, for those items
  485. whose source text line is not None.
  486. Lifted almost verbatim from traceback.py
  487. """
  488. Colors = self.Colors
  489. output_list = []
  490. for ind, (filename, lineno, name, line) in enumerate(extracted_list):
  491. normalCol, nameCol, fileCol, lineCol = (
  492. # Emphasize the last entry
  493. (Colors.normalEm, Colors.nameEm, Colors.filenameEm, Colors.line)
  494. if ind == len(extracted_list) - 1
  495. else (Colors.Normal, Colors.name, Colors.filename, "")
  496. )
  497. fns = _format_filename(filename, fileCol, normalCol, lineno=lineno)
  498. item = f"{normalCol} {fns}"
  499. if name != "<module>":
  500. item += f" in {nameCol}{name}{normalCol}\n"
  501. else:
  502. item += "\n"
  503. if line:
  504. item += f"{lineCol} {line.strip()}{normalCol}\n"
  505. output_list.append(item)
  506. return output_list
  507. def _format_exception_only(self, etype, value):
  508. """Format the exception part of a traceback.
  509. The arguments are the exception type and value such as given by
  510. sys.exc_info()[:2]. The return value is a list of strings, each ending
  511. in a newline. Normally, the list contains a single string; however,
  512. for SyntaxError exceptions, it contains several lines that (when
  513. printed) display detailed information about where the syntax error
  514. occurred. The message indicating which exception occurred is the
  515. always last string in the list.
  516. Also lifted nearly verbatim from traceback.py
  517. """
  518. have_filedata = False
  519. Colors = self.Colors
  520. output_list = []
  521. stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
  522. if value is None:
  523. # Not sure if this can still happen in Python 2.6 and above
  524. output_list.append(stype + "\n")
  525. else:
  526. if issubclass(etype, SyntaxError):
  527. have_filedata = True
  528. if not value.filename: value.filename = "<string>"
  529. if value.lineno:
  530. lineno = value.lineno
  531. textline = linecache.getline(value.filename, value.lineno)
  532. else:
  533. lineno = "unknown"
  534. textline = ""
  535. output_list.append(
  536. "%s %s%s\n"
  537. % (
  538. Colors.normalEm,
  539. _format_filename(
  540. value.filename,
  541. Colors.filenameEm,
  542. Colors.normalEm,
  543. lineno=(None if lineno == "unknown" else lineno),
  544. ),
  545. Colors.Normal,
  546. )
  547. )
  548. if textline == "":
  549. textline = py3compat.cast_unicode(value.text, "utf-8")
  550. if textline is not None:
  551. i = 0
  552. while i < len(textline) and textline[i].isspace():
  553. i += 1
  554. output_list.append(
  555. "%s %s%s\n" % (Colors.line, textline.strip(), Colors.Normal)
  556. )
  557. if value.offset is not None:
  558. s = ' '
  559. for c in textline[i:value.offset - 1]:
  560. if c.isspace():
  561. s += c
  562. else:
  563. s += " "
  564. output_list.append(
  565. "%s%s^%s\n" % (Colors.caret, s, Colors.Normal)
  566. )
  567. try:
  568. s = value.msg
  569. except Exception:
  570. s = self._some_str(value)
  571. if s:
  572. output_list.append(
  573. "%s%s:%s %s\n" % (stype, Colors.excName, Colors.Normal, s)
  574. )
  575. else:
  576. output_list.append("%s\n" % stype)
  577. # PEP-678 notes
  578. output_list.extend(f"{x}\n" for x in getattr(value, "__notes__", []))
  579. # sync with user hooks
  580. if have_filedata:
  581. ipinst = get_ipython()
  582. if ipinst is not None:
  583. ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
  584. return output_list
  585. def get_exception_only(self, etype, value):
  586. """Only print the exception type and message, without a traceback.
  587. Parameters
  588. ----------
  589. etype : exception type
  590. value : exception value
  591. """
  592. return ListTB.structured_traceback(self, etype, value)
  593. def show_exception_only(self, etype, evalue):
  594. """Only print the exception type and message, without a traceback.
  595. Parameters
  596. ----------
  597. etype : exception type
  598. evalue : exception value
  599. """
  600. # This method needs to use __call__ from *this* class, not the one from
  601. # a subclass whose signature or behavior may be different
  602. ostream = self.ostream
  603. ostream.flush()
  604. ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
  605. ostream.flush()
  606. def _some_str(self, value):
  607. # Lifted from traceback.py
  608. try:
  609. return py3compat.cast_unicode(str(value))
  610. except:
  611. return u'<unprintable %s object>' % type(value).__name__
  612. class FrameInfo:
  613. """
  614. Mirror of stack data's FrameInfo, but so that we can bypass highlighting on
  615. really long frames.
  616. """
  617. description: Optional[str]
  618. filename: Optional[str]
  619. lineno: Tuple[int]
  620. # number of context lines to use
  621. context: Optional[int]
  622. raw_lines: List[str]
  623. @classmethod
  624. def _from_stack_data_FrameInfo(cls, frame_info):
  625. return cls(
  626. getattr(frame_info, "description", None),
  627. getattr(frame_info, "filename", None), # type: ignore[arg-type]
  628. getattr(frame_info, "lineno", None), # type: ignore[arg-type]
  629. getattr(frame_info, "frame", None),
  630. getattr(frame_info, "code", None),
  631. sd=frame_info,
  632. context=None,
  633. )
  634. def __init__(
  635. self,
  636. description: Optional[str],
  637. filename: str,
  638. lineno: Tuple[int],
  639. frame,
  640. code,
  641. *,
  642. sd=None,
  643. context=None,
  644. ):
  645. self.description = description
  646. self.filename = filename
  647. self.lineno = lineno
  648. self.frame = frame
  649. self.code = code
  650. self._sd = sd
  651. self.context = context
  652. # self.lines = []
  653. if sd is None:
  654. try:
  655. # return a list of source lines and a starting line number
  656. self.raw_lines = inspect.getsourcelines(frame)[0]
  657. except OSError:
  658. self.raw_lines = [
  659. "'Could not get source, probably due dynamically evaluated source code.'"
  660. ]
  661. @property
  662. def variables_in_executing_piece(self):
  663. if self._sd:
  664. return self._sd.variables_in_executing_piece
  665. else:
  666. return []
  667. @property
  668. def lines(self):
  669. from executing.executing import NotOneValueFound
  670. try:
  671. return self._sd.lines
  672. except NotOneValueFound:
  673. class Dummy:
  674. lineno = 0
  675. is_current = False
  676. def render(self, *, pygmented):
  677. return "<Error retrieving source code with stack_data see ipython/ipython#13598>"
  678. return [Dummy()]
  679. @property
  680. def executing(self):
  681. if self._sd:
  682. return self._sd.executing
  683. else:
  684. return None
  685. # ----------------------------------------------------------------------------
  686. class VerboseTB(TBTools):
  687. """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
  688. of HTML. Requires inspect and pydoc. Crazy, man.
  689. Modified version which optionally strips the topmost entries from the
  690. traceback, to be used with alternate interpreters (because their own code
  691. would appear in the traceback)."""
  692. tb_highlight = ""
  693. tb_highlight_style = "default"
  694. def __init__(
  695. self,
  696. color_scheme: str = "Linux",
  697. call_pdb: bool = False,
  698. ostream=None,
  699. tb_offset: int = 0,
  700. long_header: bool = False,
  701. include_vars: bool = True,
  702. check_cache=None,
  703. debugger_cls=None,
  704. parent=None,
  705. config=None,
  706. ):
  707. """Specify traceback offset, headers and color scheme.
  708. Define how many frames to drop from the tracebacks. Calling it with
  709. tb_offset=1 allows use of this handler in interpreters which will have
  710. their own code at the top of the traceback (VerboseTB will first
  711. remove that frame before printing the traceback info)."""
  712. TBTools.__init__(
  713. self,
  714. color_scheme=color_scheme,
  715. call_pdb=call_pdb,
  716. ostream=ostream,
  717. parent=parent,
  718. config=config,
  719. debugger_cls=debugger_cls,
  720. )
  721. self.tb_offset = tb_offset
  722. self.long_header = long_header
  723. self.include_vars = include_vars
  724. # By default we use linecache.checkcache, but the user can provide a
  725. # different check_cache implementation. This was formerly used by the
  726. # IPython kernel for interactive code, but is no longer necessary.
  727. if check_cache is None:
  728. check_cache = linecache.checkcache
  729. self.check_cache = check_cache
  730. self.skip_hidden = True
  731. def format_record(self, frame_info: FrameInfo):
  732. """Format a single stack frame"""
  733. assert isinstance(frame_info, FrameInfo)
  734. Colors = self.Colors # just a shorthand + quicker name lookup
  735. ColorsNormal = Colors.Normal # used a lot
  736. if isinstance(frame_info._sd, stack_data.RepeatedFrames):
  737. return ' %s[... skipping similar frames: %s]%s\n' % (
  738. Colors.excName, frame_info.description, ColorsNormal)
  739. indent = " " * INDENT_SIZE
  740. em_normal = "%s\n%s%s" % (Colors.valEm, indent, ColorsNormal)
  741. tpl_call = f"in {Colors.vName}{{file}}{Colors.valEm}{{scope}}{ColorsNormal}"
  742. tpl_call_fail = "in %s%%s%s(***failed resolving arguments***)%s" % (
  743. Colors.vName,
  744. Colors.valEm,
  745. ColorsNormal,
  746. )
  747. tpl_name_val = "%%s %s= %%s%s" % (Colors.valEm, ColorsNormal)
  748. link = _format_filename(
  749. frame_info.filename,
  750. Colors.filenameEm,
  751. ColorsNormal,
  752. lineno=frame_info.lineno,
  753. )
  754. args, varargs, varkw, locals_ = inspect.getargvalues(frame_info.frame)
  755. if frame_info.executing is not None:
  756. func = frame_info.executing.code_qualname()
  757. else:
  758. func = "?"
  759. if func == "<module>":
  760. call = ""
  761. else:
  762. # Decide whether to include variable details or not
  763. var_repr = eqrepr if self.include_vars else nullrepr
  764. try:
  765. scope = inspect.formatargvalues(
  766. args, varargs, varkw, locals_, formatvalue=var_repr
  767. )
  768. call = tpl_call.format(file=func, scope=scope)
  769. except KeyError:
  770. # This happens in situations like errors inside generator
  771. # expressions, where local variables are listed in the
  772. # line, but can't be extracted from the frame. I'm not
  773. # 100% sure this isn't actually a bug in inspect itself,
  774. # but since there's no info for us to compute with, the
  775. # best we can do is report the failure and move on. Here
  776. # we must *not* call any traceback construction again,
  777. # because that would mess up use of %debug later on. So we
  778. # simply report the failure and move on. The only
  779. # limitation will be that this frame won't have locals
  780. # listed in the call signature. Quite subtle problem...
  781. # I can't think of a good way to validate this in a unit
  782. # test, but running a script consisting of:
  783. # dict( (k,v.strip()) for (k,v) in range(10) )
  784. # will illustrate the error, if this exception catch is
  785. # disabled.
  786. call = tpl_call_fail % func
  787. lvals = ''
  788. lvals_list = []
  789. if self.include_vars:
  790. try:
  791. # we likely want to fix stackdata at some point, but
  792. # still need a workaround.
  793. fibp = frame_info.variables_in_executing_piece
  794. for var in fibp:
  795. lvals_list.append(tpl_name_val % (var.name, repr(var.value)))
  796. except Exception:
  797. lvals_list.append(
  798. "Exception trying to inspect frame. No more locals available."
  799. )
  800. if lvals_list:
  801. lvals = '%s%s' % (indent, em_normal.join(lvals_list))
  802. result = f'{link}{", " if call else ""}{call}\n'
  803. if frame_info._sd is None:
  804. # fast fallback if file is too long
  805. tpl_link = "%s%%s%s" % (Colors.filenameEm, ColorsNormal)
  806. link = tpl_link % util_path.compress_user(frame_info.filename)
  807. level = "%s %s\n" % (link, call)
  808. _line_format = PyColorize.Parser(
  809. style=self.color_scheme_table.active_scheme_name, parent=self
  810. ).format2
  811. first_line = frame_info.code.co_firstlineno
  812. current_line = frame_info.lineno[0]
  813. raw_lines = frame_info.raw_lines
  814. index = current_line - first_line
  815. if index >= frame_info.context:
  816. start = max(index - frame_info.context, 0)
  817. stop = index + frame_info.context
  818. index = frame_info.context
  819. else:
  820. start = 0
  821. stop = index + frame_info.context
  822. raw_lines = raw_lines[start:stop]
  823. return "%s%s" % (
  824. level,
  825. "".join(
  826. _simple_format_traceback_lines(
  827. current_line,
  828. index,
  829. raw_lines,
  830. Colors,
  831. lvals,
  832. _line_format,
  833. )
  834. ),
  835. )
  836. # result += "\n".join(frame_info.raw_lines)
  837. else:
  838. result += "".join(
  839. _format_traceback_lines(
  840. frame_info.lines, Colors, self.has_colors, lvals
  841. )
  842. )
  843. return result
  844. def prepare_header(self, etype: str, long_version: bool = False):
  845. colors = self.Colors # just a shorthand + quicker name lookup
  846. colorsnormal = colors.Normal # used a lot
  847. exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
  848. width = min(75, get_terminal_size()[0])
  849. if long_version:
  850. # Header with the exception type, python version, and date
  851. pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
  852. date = time.ctime(time.time())
  853. head = "%s%s%s\n%s%s%s\n%s" % (
  854. colors.topline,
  855. "-" * width,
  856. colorsnormal,
  857. exc,
  858. " " * (width - len(etype) - len(pyver)),
  859. pyver,
  860. date.rjust(width),
  861. )
  862. head += (
  863. "\nA problem occurred executing Python code. Here is the sequence of function"
  864. "\ncalls leading up to the error, with the most recent (innermost) call last."
  865. )
  866. else:
  867. # Simplified header
  868. head = "%s%s" % (
  869. exc,
  870. "Traceback (most recent call last)".rjust(width - len(etype)),
  871. )
  872. return head
  873. def format_exception(self, etype, evalue):
  874. colors = self.Colors # just a shorthand + quicker name lookup
  875. colorsnormal = colors.Normal # used a lot
  876. # Get (safely) a string form of the exception info
  877. try:
  878. etype_str, evalue_str = map(str, (etype, evalue))
  879. except:
  880. # User exception is improperly defined.
  881. etype, evalue = str, sys.exc_info()[:2]
  882. etype_str, evalue_str = map(str, (etype, evalue))
  883. # PEP-678 notes
  884. notes = getattr(evalue, "__notes__", [])
  885. if not isinstance(notes, Sequence) or isinstance(notes, (str, bytes)):
  886. notes = [_safe_string(notes, "__notes__", func=repr)]
  887. # ... and format it
  888. return [
  889. "{}{}{}: {}".format(
  890. colors.excName,
  891. etype_str,
  892. colorsnormal,
  893. py3compat.cast_unicode(evalue_str),
  894. ),
  895. *(
  896. "{}{}".format(
  897. colorsnormal, _safe_string(py3compat.cast_unicode(n), "note")
  898. )
  899. for n in notes
  900. ),
  901. ]
  902. def format_exception_as_a_whole(
  903. self,
  904. etype: type,
  905. evalue: Optional[BaseException],
  906. etb: Optional[TracebackType],
  907. number_of_lines_of_context,
  908. tb_offset: Optional[int],
  909. ):
  910. """Formats the header, traceback and exception message for a single exception.
  911. This may be called multiple times by Python 3 exception chaining
  912. (PEP 3134).
  913. """
  914. # some locals
  915. orig_etype = etype
  916. try:
  917. etype = etype.__name__ # type: ignore
  918. except AttributeError:
  919. pass
  920. tb_offset = self.tb_offset if tb_offset is None else tb_offset
  921. assert isinstance(tb_offset, int)
  922. head = self.prepare_header(str(etype), self.long_header)
  923. records = (
  924. self.get_records(etb, number_of_lines_of_context, tb_offset) if etb else []
  925. )
  926. frames = []
  927. skipped = 0
  928. lastrecord = len(records) - 1
  929. for i, record in enumerate(records):
  930. if (
  931. not isinstance(record._sd, stack_data.RepeatedFrames)
  932. and self.skip_hidden
  933. ):
  934. if (
  935. record.frame.f_locals.get("__tracebackhide__", 0)
  936. and i != lastrecord
  937. ):
  938. skipped += 1
  939. continue
  940. if skipped:
  941. Colors = self.Colors # just a shorthand + quicker name lookup
  942. ColorsNormal = Colors.Normal # used a lot
  943. frames.append(
  944. " %s[... skipping hidden %s frame]%s\n"
  945. % (Colors.excName, skipped, ColorsNormal)
  946. )
  947. skipped = 0
  948. frames.append(self.format_record(record))
  949. if skipped:
  950. Colors = self.Colors # just a shorthand + quicker name lookup
  951. ColorsNormal = Colors.Normal # used a lot
  952. frames.append(
  953. " %s[... skipping hidden %s frame]%s\n"
  954. % (Colors.excName, skipped, ColorsNormal)
  955. )
  956. formatted_exception = self.format_exception(etype, evalue)
  957. if records:
  958. frame_info = records[-1]
  959. ipinst = get_ipython()
  960. if ipinst is not None:
  961. ipinst.hooks.synchronize_with_editor(frame_info.filename, frame_info.lineno, 0)
  962. return [[head] + frames + formatted_exception]
  963. def get_records(
  964. self, etb: TracebackType, number_of_lines_of_context: int, tb_offset: int
  965. ):
  966. assert etb is not None
  967. context = number_of_lines_of_context - 1
  968. after = context // 2
  969. before = context - after
  970. if self.has_colors:
  971. style = get_style_by_name(self.tb_highlight_style)
  972. style = stack_data.style_with_executing_node(style, self.tb_highlight)
  973. formatter = Terminal256Formatter(style=style)
  974. else:
  975. formatter = None
  976. options = stack_data.Options(
  977. before=before,
  978. after=after,
  979. pygments_formatter=formatter,
  980. )
  981. # Let's estimate the amount of code we will have to parse/highlight.
  982. cf: Optional[TracebackType] = etb
  983. max_len = 0
  984. tbs = []
  985. while cf is not None:
  986. try:
  987. mod = inspect.getmodule(cf.tb_frame)
  988. if mod is not None:
  989. mod_name = mod.__name__
  990. root_name, *_ = mod_name.split(".")
  991. if root_name == "IPython":
  992. cf = cf.tb_next
  993. continue
  994. max_len = get_line_number_of_frame(cf.tb_frame)
  995. except OSError:
  996. max_len = 0
  997. max_len = max(max_len, max_len)
  998. tbs.append(cf)
  999. cf = getattr(cf, "tb_next", None)
  1000. if max_len > FAST_THRESHOLD:
  1001. FIs = []
  1002. for tb in tbs:
  1003. frame = tb.tb_frame # type: ignore
  1004. lineno = (frame.f_lineno,)
  1005. code = frame.f_code
  1006. filename = code.co_filename
  1007. # TODO: Here we need to use before/after/
  1008. FIs.append(
  1009. FrameInfo(
  1010. "Raw frame", filename, lineno, frame, code, context=context
  1011. )
  1012. )
  1013. return FIs
  1014. res = list(stack_data.FrameInfo.stack_data(etb, options=options))[tb_offset:]
  1015. res = [FrameInfo._from_stack_data_FrameInfo(r) for r in res]
  1016. return res
  1017. def structured_traceback(
  1018. self,
  1019. etype: type,
  1020. evalue: Optional[BaseException],
  1021. etb: Optional[TracebackType] = None,
  1022. tb_offset: Optional[int] = None,
  1023. number_of_lines_of_context: int = 5,
  1024. ):
  1025. """Return a nice text document describing the traceback."""
  1026. formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
  1027. tb_offset)
  1028. colors = self.Colors # just a shorthand + quicker name lookup
  1029. colorsnormal = colors.Normal # used a lot
  1030. head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
  1031. structured_traceback_parts = [head]
  1032. chained_exceptions_tb_offset = 0
  1033. lines_of_context = 3
  1034. formatted_exceptions = formatted_exception
  1035. exception = self.get_parts_of_chained_exception(evalue)
  1036. if exception:
  1037. assert evalue is not None
  1038. formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
  1039. etype, evalue, etb = exception
  1040. else:
  1041. evalue = None
  1042. chained_exc_ids = set()
  1043. while evalue:
  1044. formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
  1045. chained_exceptions_tb_offset)
  1046. exception = self.get_parts_of_chained_exception(evalue)
  1047. if exception and not id(exception[1]) in chained_exc_ids:
  1048. chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
  1049. formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
  1050. etype, evalue, etb = exception
  1051. else:
  1052. evalue = None
  1053. # we want to see exceptions in a reversed order:
  1054. # the first exception should be on top
  1055. for formatted_exception in reversed(formatted_exceptions):
  1056. structured_traceback_parts += formatted_exception
  1057. return structured_traceback_parts
  1058. def debugger(self, force: bool = False):
  1059. """Call up the pdb debugger if desired, always clean up the tb
  1060. reference.
  1061. Keywords:
  1062. - force(False): by default, this routine checks the instance call_pdb
  1063. flag and does not actually invoke the debugger if the flag is false.
  1064. The 'force' option forces the debugger to activate even if the flag
  1065. is false.
  1066. If the call_pdb flag is set, the pdb interactive debugger is
  1067. invoked. In all cases, the self.tb reference to the current traceback
  1068. is deleted to prevent lingering references which hamper memory
  1069. management.
  1070. Note that each call to pdb() does an 'import readline', so if your app
  1071. requires a special setup for the readline completers, you'll have to
  1072. fix that by hand after invoking the exception handler."""
  1073. if force or self.call_pdb:
  1074. if self.pdb is None:
  1075. self.pdb = self.debugger_cls()
  1076. # the system displayhook may have changed, restore the original
  1077. # for pdb
  1078. display_trap = DisplayTrap(hook=sys.__displayhook__)
  1079. with display_trap:
  1080. self.pdb.reset()
  1081. # Find the right frame so we don't pop up inside ipython itself
  1082. if hasattr(self, "tb") and self.tb is not None: # type: ignore[has-type]
  1083. etb = self.tb # type: ignore[has-type]
  1084. else:
  1085. etb = self.tb = sys.last_traceback
  1086. while self.tb is not None and self.tb.tb_next is not None:
  1087. assert self.tb.tb_next is not None
  1088. self.tb = self.tb.tb_next
  1089. if etb and etb.tb_next:
  1090. etb = etb.tb_next
  1091. self.pdb.botframe = etb.tb_frame
  1092. # last_value should be deprecated, but last-exc sometimme not set
  1093. # please check why later and remove the getattr.
  1094. exc = sys.last_value if sys.version_info < (3, 12) else getattr(sys, "last_exc", sys.last_value) # type: ignore[attr-defined]
  1095. if exc:
  1096. self.pdb.interaction(None, exc)
  1097. else:
  1098. self.pdb.interaction(None, etb)
  1099. if hasattr(self, 'tb'):
  1100. del self.tb
  1101. def handler(self, info=None):
  1102. (etype, evalue, etb) = info or sys.exc_info()
  1103. self.tb = etb
  1104. ostream = self.ostream
  1105. ostream.flush()
  1106. ostream.write(self.text(etype, evalue, etb))
  1107. ostream.write('\n')
  1108. ostream.flush()
  1109. # Changed so an instance can just be called as VerboseTB_inst() and print
  1110. # out the right info on its own.
  1111. def __call__(self, etype=None, evalue=None, etb=None):
  1112. """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
  1113. if etb is None:
  1114. self.handler()
  1115. else:
  1116. self.handler((etype, evalue, etb))
  1117. try:
  1118. self.debugger()
  1119. except KeyboardInterrupt:
  1120. print("\nKeyboardInterrupt")
  1121. #----------------------------------------------------------------------------
  1122. class FormattedTB(VerboseTB, ListTB):
  1123. """Subclass ListTB but allow calling with a traceback.
  1124. It can thus be used as a sys.excepthook for Python > 2.1.
  1125. Also adds 'Context' and 'Verbose' modes, not available in ListTB.
  1126. Allows a tb_offset to be specified. This is useful for situations where
  1127. one needs to remove a number of topmost frames from the traceback (such as
  1128. occurs with python programs that themselves execute other python code,
  1129. like Python shells). """
  1130. mode: str
  1131. def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
  1132. ostream=None,
  1133. tb_offset=0, long_header=False, include_vars=False,
  1134. check_cache=None, debugger_cls=None,
  1135. parent=None, config=None):
  1136. # NEVER change the order of this list. Put new modes at the end:
  1137. self.valid_modes = ['Plain', 'Context', 'Verbose', 'Minimal']
  1138. self.verbose_modes = self.valid_modes[1:3]
  1139. VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
  1140. ostream=ostream, tb_offset=tb_offset,
  1141. long_header=long_header, include_vars=include_vars,
  1142. check_cache=check_cache, debugger_cls=debugger_cls,
  1143. parent=parent, config=config)
  1144. # Different types of tracebacks are joined with different separators to
  1145. # form a single string. They are taken from this dict
  1146. self._join_chars = dict(Plain='', Context='\n', Verbose='\n',
  1147. Minimal='')
  1148. # set_mode also sets the tb_join_char attribute
  1149. self.set_mode(mode)
  1150. def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
  1151. tb_offset = self.tb_offset if tb_offset is None else tb_offset
  1152. mode = self.mode
  1153. if mode in self.verbose_modes:
  1154. # Verbose modes need a full traceback
  1155. return VerboseTB.structured_traceback(
  1156. self, etype, value, tb, tb_offset, number_of_lines_of_context
  1157. )
  1158. elif mode == 'Minimal':
  1159. return ListTB.get_exception_only(self, etype, value)
  1160. else:
  1161. # We must check the source cache because otherwise we can print
  1162. # out-of-date source code.
  1163. self.check_cache()
  1164. # Now we can extract and format the exception
  1165. return ListTB.structured_traceback(
  1166. self, etype, value, tb, tb_offset, number_of_lines_of_context
  1167. )
  1168. def stb2text(self, stb):
  1169. """Convert a structured traceback (a list) to a string."""
  1170. return self.tb_join_char.join(stb)
  1171. def set_mode(self, mode: Optional[str] = None):
  1172. """Switch to the desired mode.
  1173. If mode is not specified, cycles through the available modes."""
  1174. if not mode:
  1175. new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
  1176. len(self.valid_modes)
  1177. self.mode = self.valid_modes[new_idx]
  1178. elif mode not in self.valid_modes:
  1179. raise ValueError(
  1180. "Unrecognized mode in FormattedTB: <" + mode + ">\n"
  1181. "Valid modes: " + str(self.valid_modes)
  1182. )
  1183. else:
  1184. assert isinstance(mode, str)
  1185. self.mode = mode
  1186. # include variable details only in 'Verbose' mode
  1187. self.include_vars = (self.mode == self.valid_modes[2])
  1188. # Set the join character for generating text tracebacks
  1189. self.tb_join_char = self._join_chars[self.mode]
  1190. # some convenient shortcuts
  1191. def plain(self):
  1192. self.set_mode(self.valid_modes[0])
  1193. def context(self):
  1194. self.set_mode(self.valid_modes[1])
  1195. def verbose(self):
  1196. self.set_mode(self.valid_modes[2])
  1197. def minimal(self):
  1198. self.set_mode(self.valid_modes[3])
  1199. #----------------------------------------------------------------------------
  1200. class AutoFormattedTB(FormattedTB):
  1201. """A traceback printer which can be called on the fly.
  1202. It will find out about exceptions by itself.
  1203. A brief example::
  1204. AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
  1205. try:
  1206. ...
  1207. except:
  1208. AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
  1209. """
  1210. def __call__(self, etype=None, evalue=None, etb=None,
  1211. out=None, tb_offset=None):
  1212. """Print out a formatted exception traceback.
  1213. Optional arguments:
  1214. - out: an open file-like object to direct output to.
  1215. - tb_offset: the number of frames to skip over in the stack, on a
  1216. per-call basis (this overrides temporarily the instance's tb_offset
  1217. given at initialization time."""
  1218. if out is None:
  1219. out = self.ostream
  1220. out.flush()
  1221. out.write(self.text(etype, evalue, etb, tb_offset))
  1222. out.write('\n')
  1223. out.flush()
  1224. # FIXME: we should remove the auto pdb behavior from here and leave
  1225. # that to the clients.
  1226. try:
  1227. self.debugger()
  1228. except KeyboardInterrupt:
  1229. print("\nKeyboardInterrupt")
  1230. def structured_traceback(
  1231. self,
  1232. etype: type,
  1233. evalue: Optional[BaseException],
  1234. etb: Optional[TracebackType] = None,
  1235. tb_offset: Optional[int] = None,
  1236. number_of_lines_of_context: int = 5,
  1237. ):
  1238. # tb: TracebackType or tupleof tb types ?
  1239. if etype is None:
  1240. etype, evalue, etb = sys.exc_info()
  1241. if isinstance(etb, tuple):
  1242. # tb is a tuple if this is a chained exception.
  1243. self.tb = etb[0]
  1244. else:
  1245. self.tb = etb
  1246. return FormattedTB.structured_traceback(
  1247. self, etype, evalue, etb, tb_offset, number_of_lines_of_context
  1248. )
  1249. #---------------------------------------------------------------------------
  1250. # A simple class to preserve Nathan's original functionality.
  1251. class ColorTB(FormattedTB):
  1252. """Shorthand to initialize a FormattedTB in Linux colors mode."""
  1253. def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
  1254. FormattedTB.__init__(self, color_scheme=color_scheme,
  1255. call_pdb=call_pdb, **kwargs)
  1256. class SyntaxTB(ListTB):
  1257. """Extension which holds some state: the last exception value"""
  1258. def __init__(self, color_scheme='NoColor', parent=None, config=None):
  1259. ListTB.__init__(self, color_scheme, parent=parent, config=config)
  1260. self.last_syntax_error = None
  1261. def __call__(self, etype, value, elist):
  1262. self.last_syntax_error = value
  1263. ListTB.__call__(self, etype, value, elist)
  1264. def structured_traceback(self, etype, value, elist, tb_offset=None,
  1265. context=5):
  1266. # If the source file has been edited, the line in the syntax error can
  1267. # be wrong (retrieved from an outdated cache). This replaces it with
  1268. # the current value.
  1269. if isinstance(value, SyntaxError) \
  1270. and isinstance(value.filename, str) \
  1271. and isinstance(value.lineno, int):
  1272. linecache.checkcache(value.filename)
  1273. newtext = linecache.getline(value.filename, value.lineno)
  1274. if newtext:
  1275. value.text = newtext
  1276. self.last_syntax_error = value
  1277. return super(SyntaxTB, self).structured_traceback(etype, value, elist,
  1278. tb_offset=tb_offset, context=context)
  1279. def clear_err_state(self):
  1280. """Return the current error state and clear it"""
  1281. e = self.last_syntax_error
  1282. self.last_syntax_error = None
  1283. return e
  1284. def stb2text(self, stb):
  1285. """Convert a structured traceback (a list) to a string."""
  1286. return ''.join(stb)
  1287. # some internal-use functions
  1288. def text_repr(value):
  1289. """Hopefully pretty robust repr equivalent."""
  1290. # this is pretty horrible but should always return *something*
  1291. try:
  1292. return pydoc.text.repr(value) # type: ignore[call-arg]
  1293. except KeyboardInterrupt:
  1294. raise
  1295. except:
  1296. try:
  1297. return repr(value)
  1298. except KeyboardInterrupt:
  1299. raise
  1300. except:
  1301. try:
  1302. # all still in an except block so we catch
  1303. # getattr raising
  1304. name = getattr(value, '__name__', None)
  1305. if name:
  1306. # ick, recursion
  1307. return text_repr(name)
  1308. klass = getattr(value, '__class__', None)
  1309. if klass:
  1310. return '%s instance' % text_repr(klass)
  1311. except KeyboardInterrupt:
  1312. raise
  1313. except:
  1314. return 'UNRECOVERABLE REPR FAILURE'
  1315. def eqrepr(value, repr=text_repr):
  1316. return '=%s' % repr(value)
  1317. def nullrepr(value, repr=text_repr):
  1318. return ''