Coloring exceptions from Python on a terminal

后端 未结 4 1939
天命终不由人
天命终不由人 2021-02-19 13:58

Is there an easy way to get the message of the exception to be colored on the command line? For example

def g():    f()
def f():    1/0
g()
4条回答
  •  爱一瞬间的悲伤
    2021-02-19 14:32

    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.

提交回复
热议问题