ultratb.py
1547 lines
| 55.3 KiB
| text/x-python
|
PythonLexer
Brian E Granger
|
r1234 | # -*- coding: utf-8 -*- | ||
""" | ||||
Thomas Kluyver
|
r13888 | Verbose and colourful traceback formatting. | ||
Brian E Granger
|
r1234 | |||
Thomas Kluyver
|
r13597 | **ColorTB** | ||
Brian E Granger
|
r1234 | I've always found it a bit hard to visually parse tracebacks in Python. The | ||
ColorTB class is a solution to that problem. It colors the different parts of a | ||||
traceback in a manner similar to what you would expect from a syntax-highlighting | ||||
text editor. | ||||
Thomas Kluyver
|
r12553 | Installation instructions for ColorTB:: | ||
Brian Granger
|
r2124 | import sys,ultratb | ||
sys.excepthook = ultratb.ColorTB() | ||||
Brian E Granger
|
r1234 | |||
Thomas Kluyver
|
r13597 | **VerboseTB** | ||
Brian E Granger
|
r1234 | I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds | ||
of useful info when a traceback occurs. Ping originally had it spit out HTML | ||||
and intended it for CGI programmers, but why should they have all the fun? I | ||||
altered it to spit out colored text to the terminal. It's a bit overwhelming, | ||||
but kind of neat, and maybe useful for long-running programs that you believe | ||||
are bug-free. If a crash *does* occur in that type of program you want details. | ||||
Give it a shot--you'll love it or you'll hate it. | ||||
Thomas Kluyver
|
r12553 | .. note:: | ||
Brian E Granger
|
r1234 | |||
The Verbose mode prints the variables currently visible where the exception | ||||
happened (shortening their strings if too long). This can potentially be | ||||
very slow, if you happen to have a huge data structure whose string | ||||
representation is complex to compute. Your computer may appear to freeze for | ||||
a while with cpu usage at 100%. If this occurs, you can cancel the traceback | ||||
with Ctrl-C (maybe hitting it more than once). | ||||
If you encounter this kind of situation often, you may want to use the | ||||
Verbose_novars mode instead of the regular Verbose, which avoids formatting | ||||
variables (but otherwise includes the information and context given by | ||||
Verbose). | ||||
Bernardo B. Marques
|
r4872 | |||
Matthias Bussonnier
|
r22096 | .. note:: | ||
The verbose mode print all variables in the stack, which means it can | ||||
Min ho Kim
|
r25146 | potentially leak sensitive information like access keys, or unencrypted | ||
Matthias Bussonnier
|
r22096 | password. | ||
Brian E Granger
|
r1234 | |||
Justyna Ilczuk
|
r17156 | Installation instructions for VerboseTB:: | ||
Thomas Kluyver
|
r12553 | |||
Brian Granger
|
r2124 | import sys,ultratb | ||
sys.excepthook = ultratb.VerboseTB() | ||||
Brian E Granger
|
r1234 | |||
Note: Much of the code in this module was lifted verbatim from the standard | ||||
library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'. | ||||
Thomas Kluyver
|
r12553 | Color schemes | ||
------------- | ||||
Brian E Granger
|
r1234 | The colors are defined in the class TBTools through the use of the | ||
ColorSchemeTable class. Currently the following exist: | ||||
- NoColor: allows all of this module to be used in any terminal (the color | ||||
Thomas Kluyver
|
r12553 | escapes are just dummy blank strings). | ||
Brian E Granger
|
r1234 | |||
- Linux: is meant to look good in a terminal like the Linux console (black | ||||
Thomas Kluyver
|
r12553 | or very dark background). | ||
Brian E Granger
|
r1234 | |||
- LightBG: similar to Linux but swaps dark/light colors to be more readable | ||||
Thomas Kluyver
|
r12553 | in light background terminals. | ||
Brian E Granger
|
r1234 | |||
Matthias Bussonnier
|
r22609 | - Neutral: a neutral color scheme that should be readable on both light and | ||
dark background | ||||
Brian E Granger
|
r1234 | You can implement other color schemes easily, the syntax is fairly | ||
self-explanatory. Please send back new schemes you develop to the author for | ||||
possible inclusion in future releases. | ||||
Thomas Kluyver
|
r8795 | |||
Inheritance diagram: | ||||
.. inheritance-diagram:: IPython.core.ultratb | ||||
:parts: 3 | ||||
Fernando Perez
|
r1853 | """ | ||
Brian E Granger
|
r1234 | |||
Justyna Ilczuk
|
r17158 | #***************************************************************************** | ||
Justyna Ilczuk
|
r17156 | # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu> | ||
Justyna Ilczuk
|
r17157 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> | ||
Brian E Granger
|
r1234 | # | ||
Justyna Ilczuk
|
r17157 | # Distributed under the terms of the BSD License. The full license is in | ||
# the file COPYING, distributed as part of this software. | ||||
Brian E Granger
|
r1234 | #***************************************************************************** | ||
Brian Granger
|
r2231 | |||
EtiennePelletier
|
r28242 | from collections.abc import Sequence | ||
Matthias Bussonnier
|
r28208 | import functools | ||
Brian E Granger
|
r1234 | import inspect | ||
import linecache | ||||
import pydoc | ||||
import sys | ||||
import time | ||||
import traceback | ||||
Matthias Bussonnier
|
r28208 | import types | ||
Matthias Bussonnier
|
r27361 | from types import TracebackType | ||
Matthias Bussonnier
|
r28208 | from typing import Any, List, Optional, Tuple | ||
Brian E Granger
|
r1234 | |||
Alex Hall
|
r25466 | import stack_data | ||
Alex Hall
|
r25506 | from pygments.formatters.terminal256 import Terminal256Formatter | ||
Alex Hall
|
r25548 | from pygments.styles import get_style_by_name | ||
Thomas Kluyver
|
r4758 | |||
Matthias Bussonnier
|
r28208 | import IPython.utils.colorable as colorable | ||
Brian E Granger
|
r1234 | # IPython's own modules | ||
MinRK
|
r10581 | from IPython import get_ipython | ||
from IPython.core import debugger | ||||
Brian Granger
|
r2231 | from IPython.core.display_trap import DisplayTrap | ||
Brian Granger
|
r2021 | from IPython.core.excolors import exception_colors | ||
Matthias Bussonnier
|
r28123 | from IPython.utils import PyColorize | ||
Jörgen Stenarson
|
r8299 | from IPython.utils import path as util_path | ||
Thomas Kluyver
|
r4758 | from IPython.utils import py3compat | ||
Vincent Woo
|
r22150 | from IPython.utils.terminal import get_terminal_size | ||
Matthias Bussonnier
|
r24336 | |||
Brian E Granger
|
r1234 | # Globals | ||
# amount of space to put line numbers before verbose tracebacks | ||||
INDENT_SIZE = 8 | ||||
# Default color scheme. This is used, for example, by the traceback | ||||
# formatter. When running in an actual IPython instance, the user's rc.colors | ||||
Justyna Ilczuk
|
r17156 | # value is used, but having a module global makes this functionality available | ||
Brian Granger
|
r2124 | # to users of ultratb who are NOT running inside ipython. | ||
Brian E Granger
|
r1234 | DEFAULT_SCHEME = 'NoColor' | ||
Matthias Bussonnier
|
r28123 | FAST_THRESHOLD = 10_000 | ||
Brian E Granger
|
r1234 | |||
Justyna Ilczuk
|
r17158 | # --------------------------------------------------------------------------- | ||
Brian E Granger
|
r1234 | # Code begins | ||
# Helper function -- largely belongs to VerboseTB, but we need the same | ||||
# functionality to produce a pseudo verbose TB for SyntaxErrors, so that they | ||||
# can be recognized properly by ipython.el's py-traceback-line-re | ||||
# (SyntaxErrors have to be treated specially because they have no traceback) | ||||
Justyna Ilczuk
|
r17156 | |||
Matthias Bussonnier
|
r28208 | @functools.lru_cache() | ||
def count_lines_in_py_file(filename: str) -> int: | ||||
""" | ||||
Given a filename, returns the number of lines in the file | ||||
if it ends with the extension ".py". Otherwise, returns 0. | ||||
""" | ||||
if not filename.endswith(".py"): | ||||
return 0 | ||||
else: | ||||
try: | ||||
with open(filename, "r") as file: | ||||
s = sum(1 for line in file) | ||||
except UnicodeError: | ||||
return 0 | ||||
return s | ||||
""" | ||||
Given a frame object, returns the total number of lines in the file | ||||
if the filename ends with the extension ".py". Otherwise, returns 0. | ||||
""" | ||||
def get_line_number_of_frame(frame: types.FrameType) -> int: | ||||
""" | ||||
Given a frame object, returns the total number of lines in the file | ||||
containing the frame's code object, or the number of lines in the | ||||
frame's source code if the file is not available. | ||||
Parameters | ||||
---------- | ||||
frame : FrameType | ||||
The frame object whose line number is to be determined. | ||||
Returns | ||||
------- | ||||
int | ||||
The total number of lines in the file containing the frame's | ||||
code object, or the number of lines in the frame's source code | ||||
if the file is not available. | ||||
""" | ||||
filename = frame.f_code.co_filename | ||||
if filename is None: | ||||
print("No file....") | ||||
lines, first = inspect.getsourcelines(frame) | ||||
return first + len(lines) | ||||
return count_lines_in_py_file(filename) | ||||
EtiennePelletier
|
r28242 | def _safe_string(value, what, func=str): | ||
# Copied from cpython/Lib/traceback.py | ||||
try: | ||||
return func(value) | ||||
except: | ||||
return f"<{what} {func.__name__}() failed>" | ||||
Matthias Bussonnier
|
r27361 | def _format_traceback_lines(lines, Colors, has_colors: bool, lvals): | ||
Matthias Bussonnier
|
r24334 | """ | ||
Format tracebacks lines with pointing arrow, leading numbers... | ||||
Parameters | ||||
Matthias Bussonnier
|
r25951 | ---------- | ||
lines : list[Line] | ||||
Colors | ||||
Matthias Bussonnier
|
r24334 | ColorScheme used. | ||
Matthias Bussonnier
|
r25951 | lvals : str | ||
Matthias Bussonnier
|
r24334 | Values of local variables, already colored, to inject just after the error line. | ||
""" | ||||
Brian E Granger
|
r1234 | numbers_width = INDENT_SIZE - 1 | ||
res = [] | ||||
Alex Hall
|
r25466 | for stack_line in lines: | ||
Alex Hall
|
r25468 | if stack_line is stack_data.LINE_GAP: | ||
res.append('%s (...)%s\n' % (Colors.linenoEm, Colors.Normal)) | ||||
continue | ||||
Alex Hall
|
r25506 | line = stack_line.render(pygmented=has_colors).rstrip('\n') + '\n' | ||
Alex Hall
|
r25466 | lineno = stack_line.lineno | ||
if stack_line.is_current: | ||||
Brian E Granger
|
r1234 | # This is the line with the error | ||
Alex Hall
|
r25466 | pad = numbers_width - len(str(lineno)) | ||
num = '%s%s' % (debugger.make_arrow(pad), str(lineno)) | ||||
Alex Hall
|
r25492 | start_color = Colors.linenoEm | ||
Brian E Granger
|
r1234 | else: | ||
Alex Hall
|
r25466 | num = '%*s' % (numbers_width, lineno) | ||
Alex Hall
|
r25492 | start_color = Colors.lineno | ||
martinRenou
|
r26685 | |||
Alex Hall
|
r25492 | line = '%s%s%s %s' % (start_color, num, Colors.Normal, line) | ||
Brian E Granger
|
r1234 | |||
res.append(line) | ||||
Alex Hall
|
r25466 | if lvals and stack_line.is_current: | ||
Brian E Granger
|
r1234 | res.append(lvals + '\n') | ||
return res | ||||
Matthias Bussonnier
|
r28123 | def _simple_format_traceback_lines(lnum, index, lines, Colors, lvals, _line_format): | ||
""" | ||||
Format tracebacks lines with pointing arrow, leading numbers... | ||||
Parameters | ||||
========== | ||||
lnum: int | ||||
number of the target line of code. | ||||
index: int | ||||
which line in the list should be highlighted. | ||||
lines: list[string] | ||||
Colors: | ||||
ColorScheme used. | ||||
lvals: bytes | ||||
Values of local variables, already colored, to inject just after the error line. | ||||
_line_format: f (str) -> (str, bool) | ||||
return (colorized version of str, failure to do so) | ||||
""" | ||||
numbers_width = INDENT_SIZE - 1 | ||||
res = [] | ||||
Matthias Bussonnier
|
r28124 | for i, line in enumerate(lines, lnum - index): | ||
Matthias Bussonnier
|
r28208 | # assert isinstance(line, str) | ||
Matthias Bussonnier
|
r28123 | line = py3compat.cast_unicode(line) | ||
Matthias Bussonnier
|
r28124 | new_line, err = _line_format(line, "str") | ||
Matthias Bussonnier
|
r28123 | if not err: | ||
line = new_line | ||||
if i == lnum: | ||||
# This is the line with the error | ||||
pad = numbers_width - len(str(i)) | ||||
Matthias Bussonnier
|
r28124 | num = "%s%s" % (debugger.make_arrow(pad), str(lnum)) | ||
line = "%s%s%s %s%s" % ( | ||||
Colors.linenoEm, | ||||
num, | ||||
Colors.line, | ||||
line, | ||||
Colors.Normal, | ||||
) | ||||
Matthias Bussonnier
|
r28123 | else: | ||
Matthias Bussonnier
|
r28124 | num = "%*s" % (numbers_width, i) | ||
line = "%s%s%s %s" % (Colors.lineno, num, Colors.Normal, line) | ||||
Matthias Bussonnier
|
r28123 | |||
res.append(line) | ||||
if lvals and i == lnum: | ||||
Matthias Bussonnier
|
r28124 | res.append(lvals + "\n") | ||
Matthias Bussonnier
|
r28123 | return res | ||
Brian E Granger
|
r1234 | |||
Matthias Bussonnier
|
r28124 | |||
Matthias Bussonnier
|
r27356 | def _format_filename(file, ColorFilename, ColorNormal, *, lineno=None): | ||
martinRenou
|
r26688 | """ | ||
Jason Grout
|
r27875 | Format filename lines with custom formatting from caching compiler or `File *.py` by default | ||
martinRenou
|
r26688 | |||
Parameters | ||||
---------- | ||||
file : str | ||||
martinRenou
|
r26690 | ColorFilename | ||
ColorScheme's filename coloring to be used. | ||||
ColorNormal | ||||
martinRenou
|
r26688 | ColorScheme's normal coloring to be used. | ||
""" | ||||
ipinst = get_ipython() | ||||
Jason Grout
|
r27875 | if ( | ||
ipinst is not None | ||||
and (data := ipinst.compile.format_code_name(file)) is not None | ||||
): | ||||
label, name = data | ||||
JD Smith
|
r27686 | if lineno is None: | ||
Jason Grout
|
r27875 | tpl_link = f"{{label}} {ColorFilename}{{name}}{ColorNormal}" | ||
JD Smith
|
r27686 | else: | ||
Jason Grout
|
r27875 | tpl_link = ( | ||
f"{{label}} {ColorFilename}{{name}}, line {{lineno}}{ColorNormal}" | ||||
) | ||||
martinRenou
|
r26688 | else: | ||
Jason Grout
|
r27875 | label = "File" | ||
name = util_path.compress_user( | ||||
martinRenou
|
r26688 | py3compat.cast_unicode(file, util_path.fs_encoding) | ||
) | ||||
Matthias Bussonnier
|
r27356 | if lineno is None: | ||
Jason Grout
|
r27875 | tpl_link = f"{{label}} {ColorFilename}{{name}}{ColorNormal}" | ||
Matthias Bussonnier
|
r27356 | else: | ||
Jason Grout
|
r27875 | # can we make this the more friendly ", line {{lineno}}", or do we need to preserve the formatting with the colon? | ||
tpl_link = f"{{label}} {ColorFilename}{{name}}:{{lineno}}{ColorNormal}" | ||||
martinRenou
|
r26688 | |||
Jason Grout
|
r27875 | return tpl_link.format(label=label, name=name, lineno=lineno) | ||
martinRenou
|
r26688 | |||
Brian E Granger
|
r1234 | #--------------------------------------------------------------------------- | ||
# Module classes | ||||
Matthias Bussonnier
|
r22109 | class TBTools(colorable.Colorable): | ||
Brian E Granger
|
r1234 | """Basic tools used by all traceback printer classes.""" | ||
Fernando Perez
|
r2459 | |||
Fernando Perez
|
r2838 | # Number of frames to skip when reporting tracebacks | ||
tb_offset = 0 | ||||
Matthias Bussonnier
|
r27603 | def __init__( | ||
self, | ||||
color_scheme="NoColor", | ||||
call_pdb=False, | ||||
ostream=None, | ||||
parent=None, | ||||
config=None, | ||||
*, | ||||
debugger_cls=None, | ||||
): | ||||
Brian E Granger
|
r1234 | # Whether to call the interactive pdb debugger after printing | ||
# tracebacks or not | ||||
Matthias Bussonnier
|
r22109 | super(TBTools, self).__init__(parent=parent, config=config) | ||
Brian E Granger
|
r1234 | self.call_pdb = call_pdb | ||
Fernando Perez
|
r2852 | # Output stream to write to. Note that we store the original value in | ||
# a private attribute and then make the public ostream a property, so | ||||
Min RK
|
r22742 | # that we can delay accessing sys.stdout until runtime. The way | ||
# things are written now, the sys.stdout object is dynamically managed | ||||
Fernando Perez
|
r2852 | # so a reference to it should NEVER be stored statically. This | ||
# property approach confines this detail to a single location, and all | ||||
# subclasses can simply access self.ostream for writing. | ||||
self._ostream = ostream | ||||
Brian E Granger
|
r1234 | # Create color table | ||
Fernando Perez
|
r1845 | self.color_scheme_table = exception_colors() | ||
Brian E Granger
|
r1234 | |||
self.set_colors(color_scheme) | ||||
self.old_scheme = color_scheme # save initial value for toggles | ||||
Matthias Bussonnier
|
r27603 | self.debugger_cls = debugger_cls or debugger.Pdb | ||
Brian E Granger
|
r1234 | |||
if call_pdb: | ||||
Gene Louis Kim
|
r27666 | self.pdb = self.debugger_cls() | ||
Brian E Granger
|
r1234 | else: | ||
self.pdb = None | ||||
Fernando Perez
|
r2852 | def _get_ostream(self): | ||
"""Output stream that exceptions are written to. | ||||
Valid values are: | ||||
Bernardo B. Marques
|
r4872 | |||
Fernando Perez
|
r2852 | - None: the default, which means that IPython will dynamically resolve | ||
Min RK
|
r22742 | to sys.stdout. This ensures compatibility with most tools, including | ||
Thomas Kluyver
|
r12553 | Windows (where plain stdout doesn't recognize ANSI escapes). | ||
Fernando Perez
|
r2852 | |||
- Any object with 'write' and 'flush' attributes. | ||||
""" | ||||
Thomas Kluyver
|
r22192 | return sys.stdout if self._ostream is None else self._ostream | ||
Fernando Perez
|
r2852 | |||
def _set_ostream(self, val): | ||||
assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush')) | ||||
self._ostream = val | ||||
Bernardo B. Marques
|
r4872 | |||
Fernando Perez
|
r2852 | ostream = property(_get_ostream, _set_ostream) | ||
Matthias Bussonnier
|
r27361 | @staticmethod | ||
def _get_chained_exception(exception_value): | ||||
cause = getattr(exception_value, "__cause__", None) | ||||
if cause: | ||||
return cause | ||||
if getattr(exception_value, "__suppress_context__", False): | ||||
return None | ||||
return getattr(exception_value, "__context__", None) | ||||
Quentin Peter
|
r25301 | |||
Matthias Bussonnier
|
r27361 | def get_parts_of_chained_exception( | ||
self, evalue | ||||
) -> Optional[Tuple[type, BaseException, TracebackType]]: | ||||
chained_evalue = self._get_chained_exception(evalue) | ||||
Quentin Peter
|
r25301 | |||
if chained_evalue: | ||||
return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__ | ||||
Matthias Bussonnier
|
r27361 | return None | ||
Quentin Peter
|
r25301 | |||
Matthias Bussonnier
|
r27361 | def prepare_chained_exception_message(self, cause) -> List[Any]: | ||
Quentin Peter
|
r25301 | direct_cause = "\nThe above exception was the direct cause of the following exception:\n" | ||
exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n" | ||||
if cause: | ||||
message = [[direct_cause]] | ||||
else: | ||||
message = [[exception_during_handling]] | ||||
return message | ||||
Alex Hall
|
r25506 | @property | ||
Matthias Bussonnier
|
r27361 | def has_colors(self) -> bool: | ||
Alex Hall
|
r25506 | return self.color_scheme_table.active_scheme_name.lower() != "nocolor" | ||
Justyna Ilczuk
|
r17156 | def set_colors(self, *args, **kw): | ||
Brian E Granger
|
r1234 | """Shorthand access to the color table scheme selector method.""" | ||
# Set own color table | ||||
Justyna Ilczuk
|
r17156 | self.color_scheme_table.set_active_scheme(*args, **kw) | ||
Brian E Granger
|
r1234 | # for convenience, set Colors to the active scheme | ||
self.Colors = self.color_scheme_table.active_colors | ||||
# Also set colors of debugger | ||||
Justyna Ilczuk
|
r17156 | if hasattr(self, 'pdb') and self.pdb is not None: | ||
self.pdb.set_colors(*args, **kw) | ||||
Brian E Granger
|
r1234 | |||
def color_toggle(self): | ||||
"""Toggle between the currently active color scheme and NoColor.""" | ||||
Bernardo B. Marques
|
r4872 | |||
Brian E Granger
|
r1234 | if self.color_scheme_table.active_scheme_name == 'NoColor': | ||
self.color_scheme_table.set_active_scheme(self.old_scheme) | ||||
self.Colors = self.color_scheme_table.active_colors | ||||
else: | ||||
self.old_scheme = self.color_scheme_table.active_scheme_name | ||||
self.color_scheme_table.set_active_scheme('NoColor') | ||||
self.Colors = self.color_scheme_table.active_colors | ||||
Fernando Perez
|
r2839 | def stb2text(self, stb): | ||
"""Convert a structured traceback (a list) to a string.""" | ||||
return '\n'.join(stb) | ||||
Matthias Bussonnier
|
r27361 | def text(self, etype, value, tb, tb_offset: Optional[int] = None, context=5): | ||
Fernando Perez
|
r2838 | """Return formatted traceback. | ||
Subclasses may override this if they add extra arguments. | ||||
""" | ||||
tb_list = self.structured_traceback(etype, value, tb, | ||||
tb_offset, context) | ||||
Fernando Perez
|
r2839 | return self.stb2text(tb_list) | ||
Fernando Perez
|
r2838 | |||
Matthias Bussonnier
|
r27361 | def structured_traceback( | ||
Matthias Bussonnier
|
r28167 | self, | ||
etype: type, | ||||
evalue: Optional[BaseException], | ||||
etb: Optional[TracebackType] = None, | ||||
tb_offset: Optional[int] = None, | ||||
Matthias Bussonnier
|
r28208 | number_of_lines_of_context: int = 5, | ||
Matthias Bussonnier
|
r27361 | ): | ||
Fernando Perez
|
r2838 | """Return a list of traceback frames. | ||
Must be implemented by each class. | ||||
""" | ||||
raise NotImplementedError() | ||||
Brian E Granger
|
r1234 | #--------------------------------------------------------------------------- | ||
class ListTB(TBTools): | ||||
"""Print traceback information from a traceback list, with optional color. | ||||
Bernardo B. Marques
|
r4872 | |||
Thomas Kluyver
|
r9244 | Calling requires 3 arguments: (etype, evalue, elist) | ||
as would be obtained by:: | ||||
martinRenou
|
r26685 | |||
Brian E Granger
|
r1234 | etype, evalue, tb = sys.exc_info() | ||
if tb: | ||||
elist = traceback.extract_tb(tb) | ||||
else: | ||||
elist = None | ||||
It can thus be used by programs which need to process the traceback before | ||||
printing (such as console replacements based on the code module from the | ||||
standard library). | ||||
Because they are meant to be called without a full traceback (only a | ||||
list), instances of this class can't call the interactive pdb debugger.""" | ||||
Bernardo B. Marques
|
r4872 | |||
Brian E Granger
|
r1234 | def __call__(self, etype, value, elist): | ||
Fernando Perez
|
r2860 | self.ostream.flush() | ||
self.ostream.write(self.text(etype, value, elist)) | ||||
self.ostream.write('\n') | ||||
Brian E Granger
|
r1234 | |||
Quentin Peter
|
r25370 | def _extract_tb(self, tb): | ||
if tb: | ||||
return traceback.extract_tb(tb) | ||||
else: | ||||
return None | ||||
Matthias Bussonnier
|
r27361 | def structured_traceback( | ||
self, | ||||
etype: type, | ||||
Matthias Bussonnier
|
r28167 | evalue: Optional[BaseException], | ||
Matthias Bussonnier
|
r27361 | etb: Optional[TracebackType] = None, | ||
tb_offset: Optional[int] = None, | ||||
context=5, | ||||
): | ||||
Fernando Perez
|
r2440 | """Return a color formatted string with the traceback info. | ||
Parameters | ||||
---------- | ||||
etype : exception type | ||||
Matthias Bussonnier
|
r25951 | Type of the exception raised. | ||
Quentin Peter
|
r25301 | evalue : object | ||
Matthias Bussonnier
|
r25951 | Data stored in the exception | ||
Matthias Bussonnier
|
r27361 | etb : list | TracebackType | None | ||
Matthias Bussonnier
|
r25951 | If list: List of frames, see class docstring for details. | ||
If Traceback: Traceback of the exception. | ||||
Fernando Perez
|
r2838 | tb_offset : int, optional | ||
Matthias Bussonnier
|
r25951 | Number of frames in the traceback to skip. If not given, the | ||
instance evalue is used (set in constructor). | ||||
Fernando Perez
|
r2838 | context : int, optional | ||
Matthias Bussonnier
|
r25951 | Number of lines of context information to print. | ||
Fernando Perez
|
r2838 | |||
Fernando Perez
|
r2440 | Returns | ||
------- | ||||
String with formatted exception. | ||||
""" | ||||
Quentin Peter
|
r25307 | # This is a workaround to get chained_exc_ids in recursive calls | ||
# etb should not be a tuple if structured_traceback is not recursive | ||||
Quentin Peter
|
r25303 | if isinstance(etb, tuple): | ||
etb, chained_exc_ids = etb | ||||
else: | ||||
chained_exc_ids = set() | ||||
Quentin Peter
|
r25307 | |||
Quentin Peter
|
r25301 | if isinstance(etb, list): | ||
elist = etb | ||||
elif etb is not None: | ||||
elist = self._extract_tb(etb) | ||||
else: | ||||
elist = [] | ||||
Fernando Perez
|
r2838 | tb_offset = self.tb_offset if tb_offset is None else tb_offset | ||
Matthias Bussonnier
|
r27361 | assert isinstance(tb_offset, int) | ||
Brian E Granger
|
r1234 | Colors = self.Colors | ||
Fernando Perez
|
r2838 | out_list = [] | ||
Brian E Granger
|
r1234 | if elist: | ||
Fernando Perez
|
r2838 | |||
if tb_offset and len(elist) > tb_offset: | ||||
elist = elist[tb_offset:] | ||||
Bernardo B. Marques
|
r4872 | |||
Fernando Perez
|
r2838 | out_list.append('Traceback %s(most recent call last)%s:' % | ||
Justyna Ilczuk
|
r17156 | (Colors.normalEm, Colors.Normal) + '\n') | ||
Fernando Perez
|
r2838 | out_list.extend(self._format_list(elist)) | ||
# The exception info should be a single entry in the list. | ||||
Quentin Peter
|
r25301 | lines = ''.join(self._format_exception_only(etype, evalue)) | ||
Fernando Perez
|
r2838 | out_list.append(lines) | ||
Thomas Kluyver
|
r28824 | # Find chained exceptions if we have a traceback (not for exception-only mode) | ||
if etb is not None: | ||||
exception = self.get_parts_of_chained_exception(evalue) | ||||
if exception and (id(exception[1]) not in chained_exc_ids): | ||||
chained_exception_message = ( | ||||
self.prepare_chained_exception_message(evalue.__cause__)[0] | ||||
if evalue is not None | ||||
else "" | ||||
) | ||||
etype, evalue, etb = exception | ||||
# Trace exception to avoid infinite 'cause' loop | ||||
chained_exc_ids.add(id(exception[1])) | ||||
chained_exceptions_tb_offset = 0 | ||||
out_list = ( | ||||
self.structured_traceback( | ||||
etype, | ||||
evalue, | ||||
(etb, chained_exc_ids), # type: ignore | ||||
chained_exceptions_tb_offset, | ||||
context, | ||||
) | ||||
+ chained_exception_message | ||||
+ out_list | ||||
Matthias Bussonnier
|
r28208 | ) | ||
Quentin Peter
|
r25301 | |||
Fernando Perez
|
r2838 | return out_list | ||
Brian E Granger
|
r1234 | |||
def _format_list(self, extracted_list): | ||||
"""Format a list of traceback entry tuples for printing. | ||||
Given a list of tuples as returned by extract_tb() or | ||||
extract_stack(), return a list of strings ready for printing. | ||||
Each string in the resulting list corresponds to the item with the | ||||
same index in the argument list. Each string ends in a newline; | ||||
the strings may contain internal newlines as well, for those items | ||||
whose source text line is not None. | ||||
Bernardo B. Marques
|
r4872 | |||
Brian E Granger
|
r1234 | Lifted almost verbatim from traceback.py | ||
""" | ||||
Colors = self.Colors | ||||
EtiennePelletier
|
r28278 | output_list = [] | ||
JD Smith
|
r27686 | for ind, (filename, lineno, name, line) in enumerate(extracted_list): | ||
normalCol, nameCol, fileCol, lineCol = ( | ||||
# Emphasize the last entry | ||||
(Colors.normalEm, Colors.nameEm, Colors.filenameEm, Colors.line) | ||||
if ind == len(extracted_list) - 1 | ||||
else (Colors.Normal, Colors.name, Colors.filename, "") | ||||
martinRenou
|
r26689 | ) | ||
JD Smith
|
r27686 | |||
fns = _format_filename(filename, fileCol, normalCol, lineno=lineno) | ||||
item = f"{normalCol} {fns}" | ||||
if name != "<module>": | ||||
item += f" in {nameCol}{name}{normalCol}\n" | ||||
else: | ||||
item += "\n" | ||||
Brian E Granger
|
r1234 | if line: | ||
JD Smith
|
r27686 | item += f"{lineCol} {line.strip()}{normalCol}\n" | ||
EtiennePelletier
|
r28278 | output_list.append(item) | ||
JD Smith
|
r27686 | |||
EtiennePelletier
|
r28278 | return output_list | ||
Bernardo B. Marques
|
r4872 | |||
Brian E Granger
|
r1234 | def _format_exception_only(self, etype, value): | ||
"""Format the exception part of a traceback. | ||||
The arguments are the exception type and value such as given by | ||||
sys.exc_info()[:2]. The return value is a list of strings, each ending | ||||
in a newline. Normally, the list contains a single string; however, | ||||
for SyntaxError exceptions, it contains several lines that (when | ||||
printed) display detailed information about where the syntax error | ||||
occurred. The message indicating which exception occurred is the | ||||
always last string in the list. | ||||
Bernardo B. Marques
|
r4872 | |||
Brian E Granger
|
r1234 | Also lifted nearly verbatim from traceback.py | ||
""" | ||||
Fernando Perez
|
r1568 | have_filedata = False | ||
Brian E Granger
|
r1234 | Colors = self.Colors | ||
EtiennePelletier
|
r28278 | output_list = [] | ||
Srinivas Reddy Thatiparthy
|
r23671 | stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal) | ||
Brian E Granger
|
r1234 | if value is None: | ||
Thomas Kluyver
|
r5827 | # Not sure if this can still happen in Python 2.6 and above | ||
EtiennePelletier
|
r28278 | output_list.append(stype + "\n") | ||
Brian E Granger
|
r1234 | else: | ||
Thomas Kluyver
|
r8417 | if issubclass(etype, SyntaxError): | ||
Thomas Kluyver
|
r5827 | have_filedata = True | ||
if not value.filename: value.filename = "<string>" | ||||
Jez Ng
|
r8590 | if value.lineno: | ||
lineno = value.lineno | ||||
Srinivas Reddy Thatiparthy
|
r23117 | textline = linecache.getline(value.filename, value.lineno) | ||
Jez Ng
|
r8590 | else: | ||
martinRenou
|
r26689 | lineno = "unknown" | ||
textline = "" | ||||
EtiennePelletier
|
r28278 | output_list.append( | ||
Matthias Bussonnier
|
r27356 | "%s %s%s\n" | ||
martinRenou
|
r26689 | % ( | ||
Colors.normalEm, | ||||
martinRenou
|
r26691 | _format_filename( | ||
Matthias Bussonnier
|
r27356 | value.filename, | ||
Colors.filenameEm, | ||||
Colors.normalEm, | ||||
lineno=(None if lineno == "unknown" else lineno), | ||||
martinRenou
|
r26691 | ), | ||
martinRenou
|
r26689 | Colors.Normal, | ||
) | ||||
) | ||||
if textline == "": | ||||
Srinivas Reddy Thatiparthy
|
r23671 | textline = py3compat.cast_unicode(value.text, "utf-8") | ||
Jörgen Stenarson
|
r8328 | |||
if textline is not None: | ||||
Thomas Kluyver
|
r5827 | i = 0 | ||
Jörgen Stenarson
|
r8328 | while i < len(textline) and textline[i].isspace(): | ||
Thomas Kluyver
|
r5831 | i += 1 | ||
EtiennePelletier
|
r28278 | output_list.append( | ||
"%s %s%s\n" % (Colors.line, textline.strip(), Colors.Normal) | ||||
) | ||||
Thomas Kluyver
|
r5827 | if value.offset is not None: | ||
s = ' ' | ||||
Justyna Ilczuk
|
r17156 | for c in textline[i:value.offset - 1]: | ||
Thomas Kluyver
|
r5827 | if c.isspace(): | ||
Thomas Kluyver
|
r5831 | s += c | ||
Thomas Kluyver
|
r5827 | else: | ||
EtiennePelletier
|
r28278 | s += " " | ||
output_list.append( | ||||
"%s%s^%s\n" % (Colors.caret, s, Colors.Normal) | ||||
) | ||||
Thomas Kluyver
|
r5827 | |||
try: | ||||
s = value.msg | ||||
except Exception: | ||||
s = self._some_str(value) | ||||
Brian E Granger
|
r1234 | if s: | ||
EtiennePelletier
|
r28278 | output_list.append( | ||
"%s%s:%s %s\n" % (stype, Colors.excName, Colors.Normal, s) | ||||
) | ||||
Brian E Granger
|
r1234 | else: | ||
EtiennePelletier
|
r28278 | output_list.append("%s\n" % stype) | ||
Fernando Perez
|
r1532 | |||
Zac Hatfield-Dodds
|
r28277 | # PEP-678 notes | ||
EtiennePelletier
|
r28278 | output_list.extend(f"{x}\n" for x in getattr(value, "__notes__", [])) | ||
Zac Hatfield-Dodds
|
r28277 | |||
Fernando Perez
|
r2440 | # sync with user hooks | ||
Fernando Perez
|
r2088 | if have_filedata: | ||
MinRK
|
r10581 | ipinst = get_ipython() | ||
Brian Granger
|
r2124 | if ipinst is not None: | ||
Thomas Kluyver
|
r5827 | ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0) | ||
Fernando Perez
|
r1532 | |||
EtiennePelletier
|
r28278 | return output_list | ||
Brian E Granger
|
r1234 | |||
Fernando Perez
|
r2838 | def get_exception_only(self, etype, value): | ||
"""Only print the exception type and message, without a traceback. | ||||
Bernardo B. Marques
|
r4872 | |||
Fernando Perez
|
r2838 | Parameters | ||
---------- | ||||
etype : exception type | ||||
Matthias Bussonnier
|
r27288 | value : exception value | ||
Fernando Perez
|
r2838 | """ | ||
Quentin Peter
|
r25301 | return ListTB.structured_traceback(self, etype, value) | ||
Fernando Perez
|
r2838 | |||
Brian Granger
|
r2873 | def show_exception_only(self, etype, evalue): | ||
Fernando Perez
|
r2440 | """Only print the exception type and message, without a traceback. | ||
Bernardo B. Marques
|
r4872 | |||
Fernando Perez
|
r2440 | Parameters | ||
---------- | ||||
etype : exception type | ||||
Matthias Bussonnier
|
r25951 | evalue : exception value | ||
Fernando Perez
|
r2440 | """ | ||
# This method needs to use __call__ from *this* class, not the one from | ||||
# a subclass whose signature or behavior may be different | ||||
Fernando Perez
|
r2852 | ostream = self.ostream | ||
Brian Granger
|
r2775 | ostream.flush() | ||
Fernando Perez
|
r2838 | ostream.write('\n'.join(self.get_exception_only(etype, evalue))) | ||
Brian Granger
|
r2775 | ostream.flush() | ||
Fernando Perez
|
r2440 | |||
Brian E Granger
|
r1234 | def _some_str(self, value): | ||
# Lifted from traceback.py | ||||
try: | ||||
Srinivas Reddy Thatiparthy
|
r23671 | return py3compat.cast_unicode(str(value)) | ||
Brian E Granger
|
r1234 | except: | ||
Min RK
|
r22269 | return u'<unprintable %s object>' % type(value).__name__ | ||
Brian E Granger
|
r1234 | |||
Justyna Ilczuk
|
r17156 | |||
Matthias Bussonnier
|
r28123 | class FrameInfo: | ||
""" | ||||
Mirror of stack data's FrameInfo, but so that we can bypass highlighting on | ||||
really long frames. | ||||
""" | ||||
Matthias Bussonnier
|
r28124 | description: Optional[str] | ||
Matthias Bussonnier
|
r28208 | filename: Optional[str] | ||
lineno: Tuple[int] | ||||
# number of context lines to use | ||||
context: Optional[int] | ||||
Matthias Bussonnier
|
r28653 | raw_lines: List[str] | ||
Matthias Bussonnier
|
r28123 | |||
@classmethod | ||||
def _from_stack_data_FrameInfo(cls, frame_info): | ||||
return cls( | ||||
getattr(frame_info, "description", None), | ||||
Matthias Bussonnier
|
r28208 | getattr(frame_info, "filename", None), # type: ignore[arg-type] | ||
getattr(frame_info, "lineno", None), # type: ignore[arg-type] | ||||
Matthias Bussonnier
|
r28123 | getattr(frame_info, "frame", None), | ||
getattr(frame_info, "code", None), | ||||
sd=frame_info, | ||||
Matthias Bussonnier
|
r28208 | context=None, | ||
Matthias Bussonnier
|
r28123 | ) | ||
Matthias Bussonnier
|
r28208 | def __init__( | ||
self, | ||||
description: Optional[str], | ||||
filename: str, | ||||
lineno: Tuple[int], | ||||
frame, | ||||
code, | ||||
*, | ||||
sd=None, | ||||
context=None, | ||||
): | ||||
Matthias Bussonnier
|
r28123 | self.description = description | ||
self.filename = filename | ||||
self.lineno = lineno | ||||
self.frame = frame | ||||
self.code = code | ||||
self._sd = sd | ||||
Matthias Bussonnier
|
r28208 | self.context = context | ||
Matthias Bussonnier
|
r28123 | |||
# self.lines = [] | ||||
if sd is None: | ||||
Matthias Bussonnier
|
r28653 | try: | ||
# return a list of source lines and a starting line number | ||||
self.raw_lines = inspect.getsourcelines(frame)[0] | ||||
except OSError: | ||||
self.raw_lines = [ | ||||
"'Could not get source, probably due dynamically evaluated source code.'" | ||||
] | ||||
Matthias Bussonnier
|
r28123 | |||
@property | ||||
def variables_in_executing_piece(self): | ||||
if self._sd: | ||||
return self._sd.variables_in_executing_piece | ||||
else: | ||||
return [] | ||||
@property | ||||
def lines(self): | ||||
Matthias Bussonnier
|
r28572 | from executing.executing import NotOneValueFound | ||
try: | ||||
return self._sd.lines | ||||
except NotOneValueFound: | ||||
class Dummy: | ||||
lineno = 0 | ||||
is_current = False | ||||
def render(self, *, pygmented): | ||||
return "<Error retrieving source code with stack_data see ipython/ipython#13598>" | ||||
return [Dummy()] | ||||
Matthias Bussonnier
|
r28123 | |||
@property | ||||
def executing(self): | ||||
if self._sd: | ||||
return self._sd.executing | ||||
else: | ||||
return None | ||||
Matthias Bussonnier
|
r28124 | # ---------------------------------------------------------------------------- | ||
Brian E Granger
|
r1234 | class VerboseTB(TBTools): | ||
"""A port of Ka-Ping Yee's cgitb.py module that outputs color text instead | ||||
of HTML. Requires inspect and pydoc. Crazy, man. | ||||
Modified version which optionally strips the topmost entries from the | ||||
traceback, to be used with alternate interpreters (because their own code | ||||
would appear in the traceback).""" | ||||
jsbautista
|
r28848 | tb_highlight = "bg:ansiyellow" | ||
tb_highlight_style = "default" | ||||
Matthias Bussonnier
|
r27793 | |||
Matthias Bussonnier
|
r27361 | def __init__( | ||
self, | ||||
color_scheme: str = "Linux", | ||||
call_pdb: bool = False, | ||||
ostream=None, | ||||
tb_offset: int = 0, | ||||
long_header: bool = False, | ||||
include_vars: bool = True, | ||||
check_cache=None, | ||||
debugger_cls=None, | ||||
parent=None, | ||||
config=None, | ||||
): | ||||
Brian E Granger
|
r1234 | """Specify traceback offset, headers and color scheme. | ||
Define how many frames to drop from the tracebacks. Calling it with | ||||
tb_offset=1 allows use of this handler in interpreters which will have | ||||
their own code at the top of the traceback (VerboseTB will first | ||||
remove that frame before printing the traceback info).""" | ||||
Matthias Bussonnier
|
r27603 | TBTools.__init__( | ||
self, | ||||
color_scheme=color_scheme, | ||||
call_pdb=call_pdb, | ||||
ostream=ostream, | ||||
parent=parent, | ||||
config=config, | ||||
debugger_cls=debugger_cls, | ||||
) | ||||
Brian E Granger
|
r1234 | self.tb_offset = tb_offset | ||
self.long_header = long_header | ||||
self.include_vars = include_vars | ||||
Fernando Perez
|
r3175 | # By default we use linecache.checkcache, but the user can provide a | ||
Ben Longbons
|
r27845 | # different check_cache implementation. This was formerly used by the | ||
# IPython kernel for interactive code, but is no longer necessary. | ||||
Fernando Perez
|
r3175 | if check_cache is None: | ||
check_cache = linecache.checkcache | ||||
self.check_cache = check_cache | ||||
Brian E Granger
|
r1234 | |||
Matthias Bussonnier
|
r25839 | self.skip_hidden = True | ||
Thomas Kluyver
|
r22391 | |||
Matthias Bussonnier
|
r28124 | def format_record(self, frame_info: FrameInfo): | ||
Thomas Kluyver
|
r21983 | """Format a single stack frame""" | ||
Matthias Bussonnier
|
r28123 | assert isinstance(frame_info, FrameInfo) | ||
Justyna Ilczuk
|
r17156 | Colors = self.Colors # just a shorthand + quicker name lookup | ||
ColorsNormal = Colors.Normal # used a lot | ||||
Alex Hall
|
r25467 | |||
Matthias Bussonnier
|
r28123 | if isinstance(frame_info._sd, stack_data.RepeatedFrames): | ||
Alex Hall
|
r25467 | return ' %s[... skipping similar frames: %s]%s\n' % ( | ||
Colors.excName, frame_info.description, ColorsNormal) | ||||
Arthur Moreira
|
r26986 | indent = " " * INDENT_SIZE | ||
em_normal = "%s\n%s%s" % (Colors.valEm, indent, ColorsNormal) | ||||
Matthias Bussonnier
|
r27356 | tpl_call = f"in {Colors.vName}{{file}}{Colors.valEm}{{scope}}{ColorsNormal}" | ||
tpl_call_fail = "in %s%%s%s(***failed resolving arguments***)%s" % ( | ||||
Arthur Moreira
|
r26986 | Colors.vName, | ||
Colors.valEm, | ||||
ColorsNormal, | ||||
) | ||||
tpl_name_val = "%%s %s= %%s%s" % (Colors.valEm, ColorsNormal) | ||||
Justyna Ilczuk
|
r17157 | |||
Matthias Bussonnier
|
r27356 | link = _format_filename( | ||
frame_info.filename, | ||||
Colors.filenameEm, | ||||
ColorsNormal, | ||||
lineno=frame_info.lineno, | ||||
) | ||||
Alex Hall
|
r25466 | args, varargs, varkw, locals_ = inspect.getargvalues(frame_info.frame) | ||
Matthias Bussonnier
|
r28124 | if frame_info.executing is not None: | ||
Matthias Bussonnier
|
r28123 | func = frame_info.executing.code_qualname() | ||
else: | ||||
Matthias Bussonnier
|
r28124 | func = "?" | ||
Matthias Bussonnier
|
r27356 | if func == "<module>": | ||
JD Smith
|
r27686 | call = "" | ||
Thomas Kluyver
|
r21983 | else: | ||
# Decide whether to include variable details or not | ||||
Matthias Bussonnier
|
r24336 | var_repr = eqrepr if self.include_vars else nullrepr | ||
Thomas Kluyver
|
r21983 | try: | ||
Matthias Bussonnier
|
r27356 | scope = inspect.formatargvalues( | ||
args, varargs, varkw, locals_, formatvalue=var_repr | ||||
) | ||||
call = tpl_call.format(file=func, scope=scope) | ||||
Thomas Kluyver
|
r21983 | except KeyError: | ||
# This happens in situations like errors inside generator | ||||
# expressions, where local variables are listed in the | ||||
# line, but can't be extracted from the frame. I'm not | ||||
# 100% sure this isn't actually a bug in inspect itself, | ||||
# but since there's no info for us to compute with, the | ||||
# best we can do is report the failure and move on. Here | ||||
# we must *not* call any traceback construction again, | ||||
# because that would mess up use of %debug later on. So we | ||||
# simply report the failure and move on. The only | ||||
# limitation will be that this frame won't have locals | ||||
# listed in the call signature. Quite subtle problem... | ||||
# I can't think of a good way to validate this in a unit | ||||
# test, but running a script consisting of: | ||||
# dict( (k,v.strip()) for (k,v) in range(10) ) | ||||
# will illustrate the error, if this exception catch is | ||||
# disabled. | ||||
call = tpl_call_fail % func | ||||
Matthias Bussonnier
|
r24334 | lvals = '' | ||
lvals_list = [] | ||||
Thomas Kluyver
|
r21983 | if self.include_vars: | ||
Matthias Bussonnier
|
r26712 | try: | ||
# we likely want to fix stackdata at some point, but | ||||
# still need a workaround. | ||||
fibp = frame_info.variables_in_executing_piece | ||||
for var in fibp: | ||||
lvals_list.append(tpl_name_val % (var.name, repr(var.value))) | ||||
except Exception: | ||||
lvals_list.append( | ||||
"Exception trying to inspect frame. No more locals available." | ||||
) | ||||
Matthias Bussonnier
|
r24334 | if lvals_list: | ||
lvals = '%s%s' % (indent, em_normal.join(lvals_list)) | ||||
Brian E Granger
|
r1234 | |||
JD Smith
|
r27686 | result = f'{link}{", " if call else ""}{call}\n' | ||
Matthias Bussonnier
|
r28123 | if frame_info._sd is None: | ||
# fast fallback if file is too long | ||||
Matthias Bussonnier
|
r28124 | tpl_link = "%s%%s%s" % (Colors.filenameEm, ColorsNormal) | ||
Matthias Bussonnier
|
r28123 | link = tpl_link % util_path.compress_user(frame_info.filename) | ||
Matthias Bussonnier
|
r28124 | level = "%s %s\n" % (link, call) | ||
_line_format = PyColorize.Parser( | ||||
style=self.color_scheme_table.active_scheme_name, parent=self | ||||
).format2 | ||||
Matthias Bussonnier
|
r28123 | first_line = frame_info.code.co_firstlineno | ||
current_line = frame_info.lineno[0] | ||||
Matthias Bussonnier
|
r28208 | raw_lines = frame_info.raw_lines | ||
index = current_line - first_line | ||||
if index >= frame_info.context: | ||||
start = max(index - frame_info.context, 0) | ||||
stop = index + frame_info.context | ||||
index = frame_info.context | ||||
else: | ||||
start = 0 | ||||
stop = index + frame_info.context | ||||
raw_lines = raw_lines[start:stop] | ||||
Matthias Bussonnier
|
r28124 | return "%s%s" % ( | ||
level, | ||||
"".join( | ||||
_simple_format_traceback_lines( | ||||
current_line, | ||||
Matthias Bussonnier
|
r28208 | index, | ||
raw_lines, | ||||
Matthias Bussonnier
|
r28124 | Colors, | ||
lvals, | ||||
_line_format, | ||||
) | ||||
), | ||||
) | ||||
# result += "\n".join(frame_info.raw_lines) | ||||
Matthias Bussonnier
|
r28123 | else: | ||
result += "".join( | ||||
_format_traceback_lines( | ||||
frame_info.lines, Colors, self.has_colors, lvals | ||||
) | ||||
) | ||||
Alex Hall
|
r25466 | return result | ||
Justyna Ilczuk
|
r17157 | |||
Matthias Bussonnier
|
r28167 | def prepare_header(self, etype: str, long_version: bool = False): | ||
Justyna Ilczuk
|
r17157 | colors = self.Colors # just a shorthand + quicker name lookup | ||
colorsnormal = colors.Normal # used a lot | ||||
exc = '%s%s%s' % (colors.excName, etype, colorsnormal) | ||||
Vincent Woo
|
r22150 | width = min(75, get_terminal_size()[0]) | ||
Justyna Ilczuk
|
r17157 | if long_version: | ||
# Header with the exception type, python version, and date | ||||
pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable | ||||
date = time.ctime(time.time()) | ||||
Matthias Bussonnier
|
r28167 | head = "%s%s%s\n%s%s%s\n%s" % ( | ||
colors.topline, | ||||
"-" * width, | ||||
colorsnormal, | ||||
exc, | ||||
" " * (width - len(etype) - len(pyver)), | ||||
pyver, | ||||
date.rjust(width), | ||||
) | ||||
head += ( | ||||
"\nA problem occurred executing Python code. Here is the sequence of function" | ||||
"\ncalls leading up to the error, with the most recent (innermost) call last." | ||||
) | ||||
Justyna Ilczuk
|
r17157 | else: | ||
# Simplified header | ||||
Matthias Bussonnier
|
r28167 | head = "%s%s" % ( | ||
exc, | ||||
"Traceback (most recent call last)".rjust(width - len(etype)), | ||||
) | ||||
Justyna Ilczuk
|
r17157 | |||
return head | ||||
def format_exception(self, etype, evalue): | ||||
colors = self.Colors # just a shorthand + quicker name lookup | ||||
colorsnormal = colors.Normal # used a lot | ||||
Brian E Granger
|
r1234 | # Get (safely) a string form of the exception info | ||
try: | ||||
Justyna Ilczuk
|
r17156 | etype_str, evalue_str = map(str, (etype, evalue)) | ||
Brian E Granger
|
r1234 | except: | ||
# User exception is improperly defined. | ||||
Justyna Ilczuk
|
r17156 | etype, evalue = str, sys.exc_info()[:2] | ||
etype_str, evalue_str = map(str, (etype, evalue)) | ||||
EtiennePelletier
|
r28242 | |||
EtiennePelletier
|
r28278 | # PEP-678 notes | ||
EtiennePelletier
|
r28242 | notes = getattr(evalue, "__notes__", []) | ||
if not isinstance(notes, Sequence) or isinstance(notes, (str, bytes)): | ||||
notes = [_safe_string(notes, "__notes__", func=repr)] | ||||
Brian E Granger
|
r1234 | # ... and format it | ||
EtiennePelletier
|
r28242 | return [ | ||
"{}{}{}: {}".format( | ||||
colors.excName, | ||||
etype_str, | ||||
colorsnormal, | ||||
py3compat.cast_unicode(evalue_str), | ||||
), | ||||
*( | ||||
"{}{}".format( | ||||
colorsnormal, _safe_string(py3compat.cast_unicode(n), "note") | ||||
) | ||||
for n in notes | ||||
), | ||||
] | ||||
Fernando Perez
|
r1532 | |||
Matthias Bussonnier
|
r27361 | def format_exception_as_a_whole( | ||
self, | ||||
etype: type, | ||||
Matthias Bussonnier
|
r28167 | evalue: Optional[BaseException], | ||
Matthias Bussonnier
|
r27591 | etb: Optional[TracebackType], | ||
Matthias Bussonnier
|
r27361 | number_of_lines_of_context, | ||
tb_offset: Optional[int], | ||||
): | ||||
Thomas Kluyver
|
r21983 | """Formats the header, traceback and exception message for a single exception. | ||
This may be called multiple times by Python 3 exception chaining | ||||
(PEP 3134). | ||||
""" | ||||
Justyna Ilczuk
|
r17158 | # some locals | ||
Thomas Kluyver
|
r21983 | orig_etype = etype | ||
Justyna Ilczuk
|
r17158 | try: | ||
Matthias Bussonnier
|
r28208 | etype = etype.__name__ # type: ignore | ||
Justyna Ilczuk
|
r17158 | except AttributeError: | ||
pass | ||||
tb_offset = self.tb_offset if tb_offset is None else tb_offset | ||||
Matthias Bussonnier
|
r27361 | assert isinstance(tb_offset, int) | ||
Matthias Bussonnier
|
r28208 | head = self.prepare_header(str(etype), self.long_header) | ||
Matthias Bussonnier
|
r27591 | records = ( | ||
self.get_records(etb, number_of_lines_of_context, tb_offset) if etb else [] | ||||
) | ||||
Justyna Ilczuk
|
r17158 | |||
Matthias Bussonnier
|
r25839 | frames = [] | ||
skipped = 0 | ||||
Matthias Bussonnier
|
r26053 | lastrecord = len(records) - 1 | ||
Matthias Bussonnier
|
r28123 | for i, record in enumerate(records): | ||
Matthias Bussonnier
|
r28124 | if ( | ||
not isinstance(record._sd, stack_data.RepeatedFrames) | ||||
and self.skip_hidden | ||||
): | ||||
if ( | ||||
record.frame.f_locals.get("__tracebackhide__", 0) | ||||
and i != lastrecord | ||||
): | ||||
Matthias Bussonnier
|
r25839 | skipped += 1 | ||
continue | ||||
if skipped: | ||||
Colors = self.Colors # just a shorthand + quicker name lookup | ||||
ColorsNormal = Colors.Normal # used a lot | ||||
frames.append( | ||||
" %s[... skipping hidden %s frame]%s\n" | ||||
% (Colors.excName, skipped, ColorsNormal) | ||||
) | ||||
skipped = 0 | ||||
Matthias Bussonnier
|
r28123 | frames.append(self.format_record(record)) | ||
Matthias Bussonnier
|
r25845 | if skipped: | ||
Colors = self.Colors # just a shorthand + quicker name lookup | ||||
ColorsNormal = Colors.Normal # used a lot | ||||
frames.append( | ||||
" %s[... skipping hidden %s frame]%s\n" | ||||
% (Colors.excName, skipped, ColorsNormal) | ||||
) | ||||
Hoyt Koepke
|
r21751 | |||
Justyna Ilczuk
|
r17158 | formatted_exception = self.format_exception(etype, evalue) | ||
if records: | ||||
Alex Hall
|
r25466 | frame_info = records[-1] | ||
Justyna Ilczuk
|
r17158 | ipinst = get_ipython() | ||
if ipinst is not None: | ||||
Alex Hall
|
r25466 | ipinst.hooks.synchronize_with_editor(frame_info.filename, frame_info.lineno, 0) | ||
Justyna Ilczuk
|
r17158 | |||
EtiennePelletier
|
r28242 | return [[head] + frames + formatted_exception] | ||
Justyna Ilczuk
|
r17158 | |||
Matthias Bussonnier
|
r27361 | def get_records( | ||
self, etb: TracebackType, number_of_lines_of_context: int, tb_offset: int | ||||
): | ||||
Matthias Bussonnier
|
r27591 | assert etb is not None | ||
Alex Hall
|
r25466 | context = number_of_lines_of_context - 1 | ||
after = context // 2 | ||||
before = context - after | ||||
Alex Hall
|
r25506 | if self.has_colors: | ||
jsbautista
|
r28848 | style = get_style_by_name(self.tb_highlight_style) | ||
style = stack_data.style_with_executing_node(style, self.tb_highlight) | ||||
Alex Hall
|
r25548 | formatter = Terminal256Formatter(style=style) | ||
Alex Hall
|
r25506 | else: | ||
formatter = None | ||||
options = stack_data.Options( | ||||
before=before, | ||||
after=after, | ||||
pygments_formatter=formatter, | ||||
) | ||||
Matthias Bussonnier
|
r28123 | |||
hunhoon21
|
r28157 | # Let's estimate the amount of code we will have to parse/highlight. | ||
Matthias Bussonnier
|
r28167 | cf: Optional[TracebackType] = etb | ||
Matthias Bussonnier
|
r28123 | max_len = 0 | ||
tbs = [] | ||||
while cf is not None: | ||||
hunhoon21
|
r28158 | try: | ||
Matthias Bussonnier
|
r28208 | mod = inspect.getmodule(cf.tb_frame) | ||
if mod is not None: | ||||
mod_name = mod.__name__ | ||||
root_name, *_ = mod_name.split(".") | ||||
if root_name == "IPython": | ||||
cf = cf.tb_next | ||||
continue | ||||
max_len = get_line_number_of_frame(cf.tb_frame) | ||||
hunhoon21
|
r28158 | except OSError: | ||
Matthias Bussonnier
|
r28208 | max_len = 0 | ||
max_len = max(max_len, max_len) | ||||
Matthias Bussonnier
|
r28123 | tbs.append(cf) | ||
Matthias Bussonnier
|
r28208 | cf = getattr(cf, "tb_next", None) | ||
Matthias Bussonnier
|
r28123 | |||
if max_len > FAST_THRESHOLD: | ||||
FIs = [] | ||||
for tb in tbs: | ||||
Matthias Bussonnier
|
r28208 | frame = tb.tb_frame # type: ignore | ||
Matthias Bussonnier
|
r28124 | lineno = (frame.f_lineno,) | ||
Matthias Bussonnier
|
r28123 | code = frame.f_code | ||
filename = code.co_filename | ||||
Matthias Bussonnier
|
r28208 | # TODO: Here we need to use before/after/ | ||
FIs.append( | ||||
FrameInfo( | ||||
"Raw frame", filename, lineno, frame, code, context=context | ||||
) | ||||
) | ||||
Matthias Bussonnier
|
r28123 | return FIs | ||
res = list(stack_data.FrameInfo.stack_data(etb, options=options))[tb_offset:] | ||||
res = [FrameInfo._from_stack_data_FrameInfo(r) for r in res] | ||||
return res | ||||
Bernardo B. Marques
|
r4872 | |||
Matthias Bussonnier
|
r27361 | def structured_traceback( | ||
self, | ||||
etype: type, | ||||
evalue: Optional[BaseException], | ||||
Matthias Bussonnier
|
r28208 | etb: Optional[TracebackType] = None, | ||
Matthias Bussonnier
|
r27361 | tb_offset: Optional[int] = None, | ||
number_of_lines_of_context: int = 5, | ||||
): | ||||
Justyna Ilczuk
|
r17157 | """Return a nice text document describing the traceback.""" | ||
Justyna Ilczuk
|
r17162 | formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context, | ||
tb_offset) | ||||
Justyna Ilczuk
|
r17157 | |||
Justyna Ilczuk
|
r17163 | colors = self.Colors # just a shorthand + quicker name lookup | ||
colorsnormal = colors.Normal # used a lot | ||||
Vincent Woo
|
r22150 | head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal) | ||
Justyna Ilczuk
|
r17163 | structured_traceback_parts = [head] | ||
Hugo
|
r24010 | chained_exceptions_tb_offset = 0 | ||
lines_of_context = 3 | ||||
formatted_exceptions = formatted_exception | ||||
exception = self.get_parts_of_chained_exception(evalue) | ||||
if exception: | ||||
Matthias Bussonnier
|
r27361 | assert evalue is not None | ||
Hugo
|
r24010 | formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__) | ||
etype, evalue, etb = exception | ||||
else: | ||||
evalue = None | ||||
chained_exc_ids = set() | ||||
while evalue: | ||||
formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context, | ||||
chained_exceptions_tb_offset) | ||||
Justyna Ilczuk
|
r17164 | exception = self.get_parts_of_chained_exception(evalue) | ||
Hugo
|
r24010 | |||
if exception and not id(exception[1]) in chained_exc_ids: | ||||
chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop | ||||
Justyna Ilczuk
|
r17162 | formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__) | ||
etype, evalue, etb = exception | ||||
else: | ||||
evalue = None | ||||
Justyna Ilczuk
|
r17157 | |||
Hugo
|
r24010 | # we want to see exceptions in a reversed order: | ||
# the first exception should be on top | ||||
for formatted_exception in reversed(formatted_exceptions): | ||||
structured_traceback_parts += formatted_exception | ||||
Justyna Ilczuk
|
r17162 | |||
Justyna Ilczuk
|
r17157 | return structured_traceback_parts | ||
Bernardo B. Marques
|
r4872 | |||
Matthias Bussonnier
|
r27361 | def debugger(self, force: bool = False): | ||
Brian E Granger
|
r1234 | """Call up the pdb debugger if desired, always clean up the tb | ||
reference. | ||||
Keywords: | ||||
- force(False): by default, this routine checks the instance call_pdb | ||||
Thomas Kluyver
|
r12553 | flag and does not actually invoke the debugger if the flag is false. | ||
The 'force' option forces the debugger to activate even if the flag | ||||
is false. | ||||
Brian E Granger
|
r1234 | |||
If the call_pdb flag is set, the pdb interactive debugger is | ||||
invoked. In all cases, the self.tb reference to the current traceback | ||||
is deleted to prevent lingering references which hamper memory | ||||
management. | ||||
Note that each call to pdb() does an 'import readline', so if your app | ||||
requires a special setup for the readline completers, you'll have to | ||||
fix that by hand after invoking the exception handler.""" | ||||
if force or self.call_pdb: | ||||
if self.pdb is None: | ||||
Matthias Bussonnier
|
r22911 | self.pdb = self.debugger_cls() | ||
Brian E Granger
|
r1234 | # the system displayhook may have changed, restore the original | ||
# for pdb | ||||
Brian Granger
|
r2816 | display_trap = DisplayTrap(hook=sys.__displayhook__) | ||
Brian Granger
|
r2231 | with display_trap: | ||
self.pdb.reset() | ||||
# Find the right frame so we don't pop up inside ipython itself | ||||
Matthias Bussonnier
|
r28208 | if hasattr(self, "tb") and self.tb is not None: # type: ignore[has-type] | ||
etb = self.tb # type: ignore[has-type] | ||||
Brian Granger
|
r2231 | else: | ||
etb = self.tb = sys.last_traceback | ||||
Fernando Perez
|
r2438 | while self.tb is not None and self.tb.tb_next is not None: | ||
Matthias Bussonnier
|
r27361 | assert self.tb.tb_next is not None | ||
Brian Granger
|
r2231 | self.tb = self.tb.tb_next | ||
Brian E Granger
|
r1234 | if etb and etb.tb_next: | ||
etb = etb.tb_next | ||||
self.pdb.botframe = etb.tb_frame | ||||
Matthias Bussonnier
|
r28377 | # last_value should be deprecated, but last-exc sometimme not set | ||
# please check why later and remove the getattr. | ||||
exc = sys.last_value if sys.version_info < (3, 12) else getattr(sys, "last_exc", sys.last_value) # type: ignore[attr-defined] | ||||
if exc: | ||||
self.pdb.interaction(None, exc) | ||||
else: | ||||
self.pdb.interaction(None, etb) | ||||
Brian Granger
|
r2231 | |||
Justyna Ilczuk
|
r17156 | if hasattr(self, 'tb'): | ||
Brian E Granger
|
r1234 | del self.tb | ||
def handler(self, info=None): | ||||
(etype, evalue, etb) = info or sys.exc_info() | ||||
self.tb = etb | ||||
Fernando Perez
|
r2852 | ostream = self.ostream | ||
ostream.flush() | ||||
ostream.write(self.text(etype, evalue, etb)) | ||||
ostream.write('\n') | ||||
ostream.flush() | ||||
Brian E Granger
|
r1234 | |||
# Changed so an instance can just be called as VerboseTB_inst() and print | ||||
# out the right info on its own. | ||||
def __call__(self, etype=None, evalue=None, etb=None): | ||||
"""This hook can replace sys.excepthook (for Python 2.1 or higher).""" | ||||
if etb is None: | ||||
self.handler() | ||||
else: | ||||
self.handler((etype, evalue, etb)) | ||||
try: | ||||
self.debugger() | ||||
except KeyboardInterrupt: | ||||
Thomas Kluyver
|
r13348 | print("\nKeyboardInterrupt") | ||
Brian E Granger
|
r1234 | |||
Justyna Ilczuk
|
r17156 | |||
Brian E Granger
|
r1234 | #---------------------------------------------------------------------------- | ||
Fernando Perez
|
r2838 | class FormattedTB(VerboseTB, ListTB): | ||
Brian E Granger
|
r1234 | """Subclass ListTB but allow calling with a traceback. | ||
It can thus be used as a sys.excepthook for Python > 2.1. | ||||
Also adds 'Context' and 'Verbose' modes, not available in ListTB. | ||||
Allows a tb_offset to be specified. This is useful for situations where | ||||
one needs to remove a number of topmost frames from the traceback (such as | ||||
occurs with python programs that themselves execute other python code, | ||||
like Python shells). """ | ||||
Bernardo B. Marques
|
r4872 | |||
Matthias Bussonnier
|
r27361 | mode: str | ||
Fernando Perez
|
r2852 | def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False, | ||
Bernardo B. Marques
|
r4872 | ostream=None, | ||
Fernando Perez
|
r3175 | tb_offset=0, long_header=False, include_vars=False, | ||
Matthias Bussonnier
|
r22943 | check_cache=None, debugger_cls=None, | ||
parent=None, config=None): | ||||
Brian E Granger
|
r1234 | |||
# NEVER change the order of this list. Put new modes at the end: | ||||
Dan Allan
|
r24849 | self.valid_modes = ['Plain', 'Context', 'Verbose', 'Minimal'] | ||
Brian E Granger
|
r1234 | self.verbose_modes = self.valid_modes[1:3] | ||
Fernando Perez
|
r2852 | VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, | ||
ostream=ostream, tb_offset=tb_offset, | ||||
Fernando Perez
|
r3175 | long_header=long_header, include_vars=include_vars, | ||
Matthias Bussonnier
|
r22943 | check_cache=check_cache, debugger_cls=debugger_cls, | ||
parent=parent, config=config) | ||||
Fernando Perez
|
r2839 | |||
# Different types of tracebacks are joined with different separators to | ||||
# form a single string. They are taken from this dict | ||||
Dan Allan
|
r24849 | self._join_chars = dict(Plain='', Context='\n', Verbose='\n', | ||
Minimal='') | ||||
Fernando Perez
|
r2839 | # set_mode also sets the tb_join_char attribute | ||
Brian E Granger
|
r1234 | self.set_mode(mode) | ||
Bernardo B. Marques
|
r4872 | |||
Justyna Ilczuk
|
r17157 | def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5): | ||
Fernando Perez
|
r2838 | tb_offset = self.tb_offset if tb_offset is None else tb_offset | ||
Fernando Perez
|
r2839 | mode = self.mode | ||
Brian E Granger
|
r1234 | if mode in self.verbose_modes: | ||
Brian Granger
|
r2792 | # Verbose modes need a full traceback | ||
return VerboseTB.structured_traceback( | ||||
Justyna Ilczuk
|
r17157 | self, etype, value, tb, tb_offset, number_of_lines_of_context | ||
Brian Granger
|
r2792 | ) | ||
Dan Allan
|
r24849 | elif mode == 'Minimal': | ||
return ListTB.get_exception_only(self, etype, value) | ||||
Brian E Granger
|
r1234 | else: | ||
# We must check the source cache because otherwise we can print | ||||
# out-of-date source code. | ||||
Fernando Perez
|
r3175 | self.check_cache() | ||
Brian E Granger
|
r1234 | # Now we can extract and format the exception | ||
Brian Granger
|
r2792 | return ListTB.structured_traceback( | ||
Quentin Peter
|
r25301 | self, etype, value, tb, tb_offset, number_of_lines_of_context | ||
Brian Granger
|
r2792 | ) | ||
Fernando Perez
|
r2839 | def stb2text(self, stb): | ||
"""Convert a structured traceback (a list) to a string.""" | ||||
return self.tb_join_char.join(stb) | ||||
Bernardo B. Marques
|
r4872 | |||
Matthias Bussonnier
|
r27361 | def set_mode(self, mode: Optional[str] = None): | ||
Brian E Granger
|
r1234 | """Switch to the desired mode. | ||
If mode is not specified, cycles through the available modes.""" | ||||
if not mode: | ||||
Justyna Ilczuk
|
r17157 | new_idx = (self.valid_modes.index(self.mode) + 1 ) % \ | ||
Brian E Granger
|
r1234 | len(self.valid_modes) | ||
self.mode = self.valid_modes[new_idx] | ||||
elif mode not in self.valid_modes: | ||||
Matthias Bussonnier
|
r27361 | raise ValueError( | ||
"Unrecognized mode in FormattedTB: <" + mode + ">\n" | ||||
"Valid modes: " + str(self.valid_modes) | ||||
) | ||||
Brian E Granger
|
r1234 | else: | ||
Matthias Bussonnier
|
r27361 | assert isinstance(mode, str) | ||
Brian E Granger
|
r1234 | self.mode = mode | ||
# include variable details only in 'Verbose' mode | ||||
self.include_vars = (self.mode == self.valid_modes[2]) | ||||
Fernando Perez
|
r2839 | # Set the join character for generating text tracebacks | ||
Fernando Perez
|
r3146 | self.tb_join_char = self._join_chars[self.mode] | ||
Brian E Granger
|
r1234 | |||
Justyna Ilczuk
|
r17156 | # some convenient shortcuts | ||
Brian E Granger
|
r1234 | def plain(self): | ||
self.set_mode(self.valid_modes[0]) | ||||
def context(self): | ||||
self.set_mode(self.valid_modes[1]) | ||||
def verbose(self): | ||||
self.set_mode(self.valid_modes[2]) | ||||
Dan Allan
|
r24849 | def minimal(self): | ||
self.set_mode(self.valid_modes[3]) | ||||
Justyna Ilczuk
|
r17156 | |||
Brian E Granger
|
r1234 | #---------------------------------------------------------------------------- | ||
class AutoFormattedTB(FormattedTB): | ||||
"""A traceback printer which can be called on the fly. | ||||
It will find out about exceptions by itself. | ||||
Thomas Kluyver
|
r9244 | A brief example:: | ||
Bernardo B. Marques
|
r4872 | |||
Thomas Kluyver
|
r9244 | AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux') | ||
try: | ||||
... | ||||
except: | ||||
AutoTB() # or AutoTB(out=logfile) where logfile is an open file object | ||||
Brian E Granger
|
r1234 | """ | ||
Bernardo B. Marques
|
r4872 | |||
Justyna Ilczuk
|
r17156 | def __call__(self, etype=None, evalue=None, etb=None, | ||
out=None, tb_offset=None): | ||||
Brian E Granger
|
r1234 | """Print out a formatted exception traceback. | ||
Optional arguments: | ||||
- out: an open file-like object to direct output to. | ||||
- tb_offset: the number of frames to skip over in the stack, on a | ||||
per-call basis (this overrides temporarily the instance's tb_offset | ||||
Matthias Bussonnier
|
r25951 | given at initialization time.""" | ||
Fernando Perez
|
r2440 | |||
Brian E Granger
|
r1234 | if out is None: | ||
Fernando Perez
|
r2852 | out = self.ostream | ||
Brian Granger
|
r2775 | out.flush() | ||
Fernando Perez
|
r2838 | out.write(self.text(etype, evalue, etb, tb_offset)) | ||
out.write('\n') | ||||
Brian E Granger
|
r1234 | out.flush() | ||
Fernando Perez
|
r2838 | # FIXME: we should remove the auto pdb behavior from here and leave | ||
# that to the clients. | ||||
Brian E Granger
|
r1234 | try: | ||
self.debugger() | ||||
except KeyboardInterrupt: | ||||
Thomas Kluyver
|
r13348 | print("\nKeyboardInterrupt") | ||
Brian E Granger
|
r1234 | |||
Matthias Bussonnier
|
r28124 | def structured_traceback( | ||
self, | ||||
Matthias Bussonnier
|
r28208 | etype: type, | ||
evalue: Optional[BaseException], | ||||
etb: Optional[TracebackType] = None, | ||||
tb_offset: Optional[int] = None, | ||||
number_of_lines_of_context: int = 5, | ||||
Matthias Bussonnier
|
r28124 | ): | ||
Matthias Bussonnier
|
r27361 | # tb: TracebackType or tupleof tb types ? | ||
Brian E Granger
|
r1234 | if etype is None: | ||
Matthias Bussonnier
|
r28208 | etype, evalue, etb = sys.exc_info() | ||
if isinstance(etb, tuple): | ||||
Quentin Peter
|
r25370 | # tb is a tuple if this is a chained exception. | ||
Matthias Bussonnier
|
r28208 | self.tb = etb[0] | ||
Quentin Peter
|
r25371 | else: | ||
Matthias Bussonnier
|
r28208 | self.tb = etb | ||
Brian Granger
|
r2792 | return FormattedTB.structured_traceback( | ||
Matthias Bussonnier
|
r28208 | self, etype, evalue, etb, tb_offset, number_of_lines_of_context | ||
) | ||||
Brian E Granger
|
r1234 | |||
Justyna Ilczuk
|
r17156 | |||
Brian E Granger
|
r1234 | #--------------------------------------------------------------------------- | ||
Brian Granger
|
r2792 | |||
Brian E Granger
|
r1234 | # A simple class to preserve Nathan's original functionality. | ||
class ColorTB(FormattedTB): | ||||
"""Shorthand to initialize a FormattedTB in Linux colors mode.""" | ||||
Justyna Ilczuk
|
r17156 | |||
Matthias Bussonnier
|
r21789 | def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs): | ||
Justyna Ilczuk
|
r17156 | FormattedTB.__init__(self, color_scheme=color_scheme, | ||
Matthias Bussonnier
|
r21789 | call_pdb=call_pdb, **kwargs) | ||
Brian E Granger
|
r1234 | |||
Brian Granger
|
r2792 | |||
class SyntaxTB(ListTB): | ||||
"""Extension which holds some state: the last exception value""" | ||||
Matthias Bussonnier
|
r22943 | def __init__(self, color_scheme='NoColor', parent=None, config=None): | ||
ListTB.__init__(self, color_scheme, parent=parent, config=config) | ||||
Brian Granger
|
r2792 | self.last_syntax_error = None | ||
def __call__(self, etype, value, elist): | ||||
self.last_syntax_error = value | ||||
Justyna Ilczuk
|
r17157 | |||
Justyna Ilczuk
|
r17156 | ListTB.__call__(self, etype, value, elist) | ||
Brian Granger
|
r2792 | |||
Thomas Kluyver
|
r12544 | def structured_traceback(self, etype, value, elist, tb_offset=None, | ||
context=5): | ||||
# If the source file has been edited, the line in the syntax error can | ||||
# be wrong (retrieved from an outdated cache). This replaces it with | ||||
# the current value. | ||||
Thomas Kluyver
|
r12951 | if isinstance(value, SyntaxError) \ | ||
Srinivas Reddy Thatiparthy
|
r23037 | and isinstance(value.filename, str) \ | ||
Thomas Kluyver
|
r12545 | and isinstance(value.lineno, int): | ||
Thomas Kluyver
|
r12544 | linecache.checkcache(value.filename) | ||
Srinivas Reddy Thatiparthy
|
r23117 | newtext = linecache.getline(value.filename, value.lineno) | ||
Thomas Kluyver
|
r12544 | if newtext: | ||
value.text = newtext | ||||
Thomas Kluyver
|
r22204 | self.last_syntax_error = value | ||
Thomas Kluyver
|
r12544 | return super(SyntaxTB, self).structured_traceback(etype, value, elist, | ||
Justyna Ilczuk
|
r17156 | tb_offset=tb_offset, context=context) | ||
Thomas Kluyver
|
r12544 | |||
Brian Granger
|
r2792 | def clear_err_state(self): | ||
"""Return the current error state and clear it""" | ||||
e = self.last_syntax_error | ||||
self.last_syntax_error = None | ||||
return e | ||||
Fernando Perez
|
r2839 | def stb2text(self, stb): | ||
"""Convert a structured traceback (a list) to a string.""" | ||||
return ''.join(stb) | ||||
Fernando Perez
|
r2838 | |||
Justyna Ilczuk
|
r17157 | # some internal-use functions | ||
def text_repr(value): | ||||
"""Hopefully pretty robust repr equivalent.""" | ||||
# this is pretty horrible but should always return *something* | ||||
try: | ||||
Matthias Bussonnier
|
r28208 | return pydoc.text.repr(value) # type: ignore[call-arg] | ||
Justyna Ilczuk
|
r17157 | except KeyboardInterrupt: | ||
raise | ||||
except: | ||||
try: | ||||
return repr(value) | ||||
except KeyboardInterrupt: | ||||
raise | ||||
except: | ||||
try: | ||||
# all still in an except block so we catch | ||||
# getattr raising | ||||
name = getattr(value, '__name__', None) | ||||
if name: | ||||
# ick, recursion | ||||
return text_repr(name) | ||||
klass = getattr(value, '__class__', None) | ||||
if klass: | ||||
return '%s instance' % text_repr(klass) | ||||
except KeyboardInterrupt: | ||||
raise | ||||
except: | ||||
return 'UNRECOVERABLE REPR FAILURE' | ||||
def eqrepr(value, repr=text_repr): | ||||
return '=%s' % repr(value) | ||||
def nullrepr(value, repr=text_repr): | ||||
return '' | ||||