Color exception from Python on terminal

Is there an easy way to get the message that the exception will be colored on the command line? for example

def g(): f() def f(): 1/0 g() 

Gives an error

 Traceback (most recent call last): File "test.py", line 3, in <module> g() File "test.py", line 1, in g def g(): f() File "test.py", line 2, in f def f(): 1/0 ZeroDivisionError: integer division or modulo by zero 

I would like for “ integer division or modulo zero ” to be colored or highlighted on the terminal so that I can quickly select it from a long trace (Linux only). Ideally, I would not want to write a custom class for each Exception, but somehow caught and formatted all kinds.

EDIT: The question related to comments contains examples of how to solve the problem with external software, but I'm interested in the internal Python solution.

+10
source share
4 answers

You can assign a custom function to the sys.excepthook handler. The function is called whenever there is an unhandled exception (for example, exiting from 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 trace text to text formatted with ANSI coloring before writing it to stderr .

Someone turned this into a project that detects terminal support and allows you to set the style of the fragments, see colored-traceback.py .

+12
source

Another way to do this was found using the IPython module, which most likely depends on the fact that everyone is already installed:

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

Take a look at the colorama (or any other coloring) module. Then you can wrap the whole application:

 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 
+2
source

This makes the decision @freakish shared and makes the coloring part of the exception, rather than requiring the user to add color to each exception message. Obviously, it only works for custom exceptions, so it may not be exactly what the 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 a trace with "some error message" in red. Having "Error" as the base class means that you can throw other exceptions that will inherit the coloring of the message.

+1
source

All Articles