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