How to colorize the output of Python errors in the Gnome terminal?

前端 未结 4 1405
难免孤独
难免孤独 2021-02-09 19:17

Note: I am asking this question after researching how to actually do it. Other questions which are somewhat similar, but actually differ from my question relate to:

    <
4条回答
  •  被撕碎了的回忆
    2021-02-09 19:47

    FWIW, you can wrap the script in a main function, and call the main function within a try ... except block, get the error message, colourize it and print it;

    To get the error message you need a call to sys.exc_info. traceback.format_exception formats the stack-trace and the exception information. Using basic regex you can wrap every ..Err.. inside a \033[91m...Err...\033[0m which turns the colour into red:

    def main():
       with open('xxx.txt', 'r') as fin:
            return fin.read()
    
    try:
        main()
    except:
        import re
        from sys import exc_info
        from traceback import format_exception
    
        RED, REV = r'\033[91m', r'\033[0m'
        err = ''.join(format_exception(*exc_info()))
        print(re.sub(r'(\w*Err\w*)', RED + r'\1' + REV, err))
    

    Result:

    err

提交回复
热议问题