Printing to STDOUT and log file while removing ANSI color codes

Posted by Arrieta on Stack Overflow See other posts from Stack Overflow or by Arrieta
Published on 2010-05-23T22:00:24Z Indexed on 2010/05/23 22:00 UTC
Read the original article Hit count: 273

Filed under:
|
|
|

I have the following functions for colorizing my screen messages:

def error(string):
    return '\033[31;1m' + string + '\033[0m'

def standout(string):
    return '\033[34;1m' + string + '\033[0m'

I use them as follows:

print error('There was a problem with the program')
print "This is normal " + standout("and this stands out")

I want to log the output to a file (in addition to STDOUT) WITHOUT the ANSI color codes, hopefully without having to add a second "logging" line to each print statement.

The reason is that if you simply python program.py > out then the file out will have the ANSI color codes, which look terrible if you open in a plain text editor.

Any advice?

© Stack Overflow or respective owner

Related posts about python

Related posts about logging