Coloring exceptions from Python on a terminal

后端 未结 4 886
天命终不由人
天命终不由人 2021-02-19 14:02

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:15

    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.

提交回复
热议问题