Module: core.ultratb — IPython 5.3.0 documentation

# Module: `core.ultratb`

Verbose and colourful traceback formatting.

ColorTB

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.

Installation instructions for ColorTB:

    import sys,ultratb
    sys.excepthook = ultratb.ColorTB()

VerboseTB

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.

Note

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).

Note

The verbose mode print all variables in the stack, which means it can potentially leak sensitive information like access keys, or unencryted password.

Installation instructions for VerboseTB:

    import sys,ultratb
    sys.excepthook = ultratb.VerboseTB()

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’.

## Color schemes

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 escapes are just dummy blank strings).
> - Linux: is meant to look good in a terminal like the Linux console (black or very dark background).
> - LightBG: similar to Linux but swaps dark/light colors to be more readable in light background terminals.
> - Neutral: a neutral color scheme that should be readable on both light and dark background

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.

Inheritance diagram:

## 7 Classes

class `IPython.core.ultratb.` `TBTools`(color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None)

  Bases: `IPython.utils.colorable.Colorable`

  Basic tools used by all traceback printer classes.

  `__init__`(color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None)
  `color_toggle`()

    Toggle between the currently active color scheme and NoColor.

  `ostream`

    Output stream that exceptions are written to.

    Valid values are:

    - None: the default, which means that IPython will dynamically resolve to sys.stdout. This ensures compatibility with most tools, including Windows (where plain stdout doesn’t recognize ANSI escapes).
    - Any object with ‘write’ and ‘flush’ attributes.
  `set_colors`(*args, **kw)

    Shorthand access to the color table scheme selector method.

  `stb2text`(stb)

    Convert a structured traceback (a list) to a string.

  `structured_traceback`(etype, evalue, tb, tb_offset=None, context=5, mode=None)

    Return a list of traceback frames.

    Must be implemented by each class.

  `text`(etype, value, tb, tb_offset=None, context=5)

    Return formatted traceback.

    Subclasses may override this if they add extra arguments.

class `IPython.core.ultratb.` `ListTB`(color_scheme='NoColor', call_pdb=False, ostream=None, parent=None)

  Bases: `IPython.core.ultratb.TBTools`

  Print traceback information from a traceback list, with optional color.

  Calling requires 3 arguments: (etype, evalue, elist) as would be obtained by:

      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.

  `__init__`(color_scheme='NoColor', call_pdb=False, ostream=None, parent=None)
  `get_exception_only`(etype, value)

    Only print the exception type and message, without a traceback.

    Parameters: | etype (exception type) – value (exception value) –

  `show_exception_only`(etype, evalue)

    Only print the exception type and message, without a traceback.

    Parameters: | etype (exception type) – value (exception value) –

  `structured_traceback`(etype, value, elist, tb_offset=None, context=5)

    Return a color formatted string with the traceback info.

    Parameters: | etype (exception type) – Type of the exception raised. value (object) – Data stored in the exception elist (list) – List of frames, see class docstring for details. tb_offset (int, optional) – Number of frames in the traceback to skip. If not given, the instance value is used (set in constructor). context (int, optional) – Number of lines of context information to print.
    Returns: |
    Return type: | String with formatted exception.

class `IPython.core.ultratb.` `VerboseTB`(color_scheme='Linux', call_pdb=False, ostream=None, tb_offset=0, long_header=False, include_vars=True, check_cache=None, debugger_cls=None)

  Bases: `IPython.core.ultratb.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).

  `__init__`(color_scheme='Linux', call_pdb=False, ostream=None, tb_offset=0, long_header=False, include_vars=True, check_cache=None, debugger_cls=None)

    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).

  `debugger`(force=False)

    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 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.

    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.

  `format_exception_as_a_whole`(etype, evalue, etb, number_of_lines_of_context, tb_offset)

    Formats the header, traceback and exception message for a single exception.

    This may be called multiple times by Python 3 exception chaining (PEP 3134).

  `format_record`(frame, file, lnum, func, lines, index)

    Format a single stack frame

  `format_records`(records, last_unique, recursion_repeat)

    Format the stack frames of the traceback

  `structured_traceback`(etype, evalue, etb, tb_offset=None, number_of_lines_of_context=5)

    Return a nice text document describing the traceback.

class `IPython.core.ultratb.` `FormattedTB`(mode='Plain', color_scheme='Linux', call_pdb=False, ostream=None, tb_offset=0, long_header=False, include_vars=False, check_cache=None, debugger_cls=None)

  Bases: `IPython.core.ultratb.VerboseTB`, `IPython.core.ultratb.ListTB`

  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).

  `__init__`(mode='Plain', color_scheme='Linux', call_pdb=False, ostream=None, tb_offset=0, long_header=False, include_vars=False, check_cache=None, debugger_cls=None)
  `set_mode`(mode=None)

    Switch to the desired mode.

    If mode is not specified, cycles through the available modes.

  `stb2text`(stb)

    Convert a structured traceback (a list) to a string.

class `IPython.core.ultratb.` `AutoFormattedTB`(mode='Plain', color_scheme='Linux', call_pdb=False, ostream=None, tb_offset=0, long_header=False, include_vars=False, check_cache=None, debugger_cls=None)

  Bases: `IPython.core.ultratb.FormattedTB`

  A traceback printer which can be called on the fly.

  It will find out about exceptions by itself.

  A brief example:

      AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
      try:
        ...
      except:
        AutoTB()  # or AutoTB(out=logfile) where logfile is an open file object

class `IPython.core.ultratb.` `ColorTB`(color_scheme='Linux', call_pdb=0, **kwargs)

  Bases: `IPython.core.ultratb.FormattedTB`

  Shorthand to initialize a FormattedTB in Linux colors mode.

  `__init__`(color_scheme='Linux', call_pdb=0, **kwargs)

class `IPython.core.ultratb.` `SyntaxTB`(color_scheme='NoColor')

  Bases: `IPython.core.ultratb.ListTB`

  Extension which holds some state: the last exception value

  `__init__`(color_scheme='NoColor')
  `clear_err_state`()

    Return the current error state and clear it

  `stb2text`(stb)

    Convert a structured traceback (a list) to a string.

## 10 Functions

`IPython.core.ultratb.` `inspect_error`()

  Print a message about internal inspect errors.

  These are unfortunately quite common.

`IPython.core.ultratb.` `findsource`(object)

  Return the entire source file and starting line number for an object.

  The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.

  FIXED version with which we monkeypatch the stdlib to work around a bug.

`IPython.core.ultratb.` `getargs`(co)

  Get information about the arguments accepted by a code object.

  Three things are returned: (args, varargs, varkw), where ‘args’ is a list of argument names (possibly containing nested lists), and ‘varargs’ and ‘varkw’ are the names of the * and ** arguments or None.

`IPython.core.ultratb.` `with_patch_inspect`(f)

  decorator for monkeypatching inspect.findsource

`IPython.core.ultratb.` `fix_frame_records_filenames`(records)

  Try to fix the filenames in each record from inspect.getinnerframes().

  Particularly, modules loaded from within zip files have useless filenames attached to their code object, and inspect.getinnerframes() just uses it.

`IPython.core.ultratb.` `is_recursion_error`(etype, value, records)

`IPython.core.ultratb.` `find_recursion`(etype, value, records)

  Identify the repeating stack frames from a RecursionError traceback

  ‘records’ is a list as returned by VerboseTB.get_records()

  Returns (last_unique, repeat_length)

`IPython.core.ultratb.` `text_repr`(value)

  Hopefully pretty robust repr equivalent.

`IPython.core.ultratb.` `eqrepr`(value, repr=<function text_repr>)

`IPython.core.ultratb.` `nullrepr`(value, repr=<function text_repr>)