2010-05-23 101 views
7

我有着色我的屏幕显示信息如下功能:打印到标准输出和日志文件,同时删除ANSI颜色码

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语句添加第二个“日志记录”行。

原因是,如果你只是python program.py > out那么文件out将具有ANSI颜色代码,如果你打开一个纯文本编辑器,这看起来很可怕。

有什么建议吗?

回答

9

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默认参数之一,因为默认参数在编译评估而不是像C++一样在运行时运行...

此外,如果您真的需要,也可以显式覆盖该行为,尽管这不会让您在重定向时操纵stdout本身。有什么理由不使用logging模块(也许你不知道)?

+0

出色答卷 - 这可能正是我需要的。我实际上使用日志记录模块,但希望让用户可以选择重定向输出并获取可读文件。日志本身是由日志模块创建的(并且你的方法我很可能会得到我想要的)。 – Escualo 2010-05-23 22:48:13

+0

我刚刚测试过你的方法,它的工作原理与预期完全一致。非常感谢! – Escualo 2010-05-23 22:50:59

5

如果你希望打印到终端和日志文件,那么我建议使用日志记录模块。你甚至可以定义自定义格式,所以记录到文件可以清除终端代码:

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

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

1

unubtu的回答是伟大的,但我认为MyFormatter需要稍作修改,以强制执行的格式()方法格式化

class MyFormatter(logging.Formatter): 
     def format(self,record): 
      msg = super(MyFormatter, self).format(record) 
      return plain(msg) 
相关问题