Python – Excludes ANSI escape sequences from the output log file

Excludes ANSI escape sequences from the output log file… here is a solution to the problem.

Excludes ANSI escape sequences from the output log file

I’ve set a class of colors to make the standard output easier to read when there is a warning. I also want to write all print statements to a log file.

# Colour set up
class colours:
    warning = '\033[93m'
    colour1 = '\033[94m'
    colour2 = '\033[1m'
    terminate = '\033[0m'

# Logger set up
class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout
        self.log = open(“output.log”, "a")

def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

sys.stdout = Logger()

# Example
print colours.warning + ‘WARNING!’ + colours.terminate

*in colour*:$ WARNING!

*in output.log*: [93mWARNING!

Is there any way to write characters that would also color the output.log file, or print to standard output in color without including “[94m” in the log file? For the convenience of users, I don’t want to ask to install any non-native python packages.

Solution

Use something like >\x1b\[[0-9; Does a regular expression like ]*m strip ANSI code when writing to an output.log object?

Namely

import re

ansi_re = re.compile(r'\x1b\[[0-9; ]*m')

# ...

self.log.write(re.sub(ansi_re, '', message))

Related Problems and Solutions