我有以下功能来着色我的屏幕消息:

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")

我想在没有ANSI颜色代码的情况下将输出记录到文件(除了Stdout之外),希望无需在每个文件中添加第二个“记录”行 print 陈述。

原因是,如果您只是 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 ++中进行评估。

另外,如果您确实需要,则可以明确地覆盖行为,尽管这并不能在重定向时操纵自己的Stdout本身。有什么原因为什么您不使用 logging 模块(也许您不知道)?

其他提示

如果您想打印到终端和日志文件,那么我建议使用日志记录模块。您甚至可以定义自定义格式化器,因此登录文件可以清除终端代码:

import optparse
import logging

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

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

def plain(string):
    return string.replace('\033[34;1m','').replace('\033[31;1m','').replace('\033[0m','')

if __name__=='__main__':
    logging.basicConfig(level=logging.DEBUG,
                        format='%(message)s',
                        filemode='w')
    logger=logging.getLogger(__name__)    
    def parse_options():    
        usage = 'usage: %prog [Options]'
        parser = optparse.OptionParser()
        parser.add_option('-l', '--logfile', dest='logfile', 
                          help='use log file')
        opt,args = parser.parse_args()
        return opt,args
    opt,args=parse_options()
    if opt.logfile:
        class MyFormatter(logging.Formatter):
            def format(self,record):
                return plain(record.msg)
        fh = logging.FileHandler(opt.logfile)
        fh.setLevel(logging.INFO)
        formatter = MyFormatter('%(message)s')
        fh.setFormatter(formatter)
        logging.getLogger('').addHandler(fh)

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

test.py 仅印刷到终端。

test.py -l test.out 打印到终端和文件 test.out.

在所有情况下,终端的文本都有颜色代码,而日志记录则没有。

下面的unubtu的答案很棒,但我认为myformatter需要进行较小的修改来以格式()方法执行格式

class MyFormatter(logging.Formatter):
        def format(self,record):
            msg = super(MyFormatter, self).format(record)
            return plain(msg)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top