打印到STDOUT和日志文件,同时删除ANSI颜色代码 [英] Printing to STDOUT and log file while removing ANSI color codes
问题描述
我具有以下功能来使屏幕消息着色:
def error(string):
return '\033[31;1m' + string + '\033[0m'
def standout(string):
return '\033[34;1m' + string + '\033[0m'
我按如下方式使用它们:
print error('There was a problem with the program')
print "This is normal " + standout("and this stands out")
我想将输出记录到文件中(除了STDOUT之外),而没有ANSI颜色代码,希望不必在每个print
语句中添加第二条"logging"行.
原因是,如果只是简单地python program.py > out
,则文件out
将具有ANSI颜色代码,如果在纯文本编辑器中打开该代码会很糟糕.
有什么建议吗?
sys.stdout.isatty
函数可能会提供帮助:
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
实际上,这是我可以想到使用未设置为None
的默认参数的少数几种用法之一,因为默认参数是在Python的编译时而不是在C ++的运行时求值的.>
如果确实需要,也可以显式覆盖该行为,尽管这样做并不能让您在重定向标准输出本身时对其进行操作.有什么理由不使用logging
模块(也许您不知道)吗?
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?
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)?
这篇关于打印到STDOUT和日志文件,同时删除ANSI颜色代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!