1
votes

I have set up a class of colours to make the stdout easier to read in case of warnings. 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 either write characters that will also colour the output.log file or print in colour to the stdout but not include '[94m' in the log file? I’d prefer not to require an install of any non-native python packages for user ease.

1
For ease of use you should use a logging library, not build your own. They've already solved such problems. A logging library for example will use different code for different targets, and won't force the caller to include console-specific escape sequencesPanagiotis Kanavos
If you want to emulate what a logging library does, you should check the logging level inside Logger and emit escape sequences only for Warning messages, only to the terminal. This means that the logging level can't be part of the message either, it has to be a separate parameterPanagiotis Kanavos
Thanks a lot for your input, I will read up on logger!Massive_Shed

1 Answers

3
votes

Use a regexp like \x1b\[[0-9;]*m to strip out the ANSI codes when writing to the output.log object?

I.e.

import re

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

# ...

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