2010-05-23 95 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) 
相關問題