Coloring exceptions from Python on a terminal

Found another way to do this using the IPython module which is likely a dependency that everyone already has installed:

from IPython.core.ultratb import ColorTB
c = ColorTB()
exc = sys.exc_info()
print(''.join(c.structured_traceback(*exc)))

This takes the solution @freakish shared and makes the colorization part of the exception instead of requiring the user to add color to each exception message. Obviously, it only works for custom exceptions, so it may not be exactly what OP was looking for.

from colorama import Fore, init
init()

class Error (Exception):
    def __init__ (self, message):
        super().__init__(Fore.RED + message)

class BadConfigFile (Error):
    pass

raise BadConfigFile("some error message")

This will print the traceback with "some error message" in red. Having 'Error' as a base class means you can create other exceptions that will all inherit the colorization of the message.


Have a look at colorama ( or any other coloring ) module. Then you can wrap you're entire app with:

import traceback
from colorama import Fore, init
init( )

try:
    // your app
except Exception:
    print Fore.RED + traceback.format_exc( ) + Fore.RESET
    // possibly raise again or log to db

You can assign a custom function to the sys.excepthook handler. The function is called whenever there is a unhandled exception (so one that exits the interpreter).

def set_highlighted_excepthook():
    import sys, traceback
    from pygments import highlight
    from pygments.lexers import get_lexer_by_name
    from pygments.formatters import TerminalFormatter

    lexer = get_lexer_by_name("pytb" if sys.version_info.major < 3 else "py3tb")
    formatter = TerminalFormatter()

    def myexcepthook(type, value, tb):
        tbtext = ''.join(traceback.format_exception(type, value, tb))
        sys.stderr.write(highlight(tbtext, lexer, formatter))

    sys.excepthook = myexcepthook

set_highlighted_excepthook()

This version uses the pygments library to convert the traceback text into one formatted with ANSI coloring, before writing it to stderr.

Someone turned this into a project that detects terminal support and lets you set the pygments style, see colored-traceback.py.