Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing to STDOUT and log file while removing ANSI color codes

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?

like image 374
Escualo Avatar asked May 23 '10 22:05

Escualo


People also ask

How do I delete ANSI characters?

You can use regexes to remove the ANSI escape sequences from a string in Python. Simply substitute the escape sequences with an empty string using re. sub(). The regex you can use for removing ANSI escape sequences is: '(\x9B|\x1B\[)[0-?]

What is <UNK>x1B?

The code containing only 0 (being \x1B[0m ) will reset any style property of the font. Most of the time, you will print a code changing the style of your terminal, then print a certain string, and then, the reset code.


1 Answers

The sys.stdout.isatty function might be able to help:

from sys import stdout

def error(string, is_tty=stdout.isatty()):
    return ('\033[31;1m' + string + '\033[0m') if is_tty else string

def standout(string, is_tty=stdout.isatty()):
    return ('\033[34;1m' + string + '\033[0m') if is_tty else string

That's actually one of the few uses I can think of to use a default argument that isn't set to None because default arguments are evaluated at compile time in Python rather than at runtime like in C++...

Also the behaviour can be explicitly overridden if you really need to, though that doesn't let you manipulate stdout itself when it's redirected. Is there any reason why you're not using the logging module (perhaps you didn't know about it)?

like image 141
Dustin Avatar answered Sep 30 '22 00:09

Dustin