如果你希望打印到終端和日誌文件,那麼我建議使用日誌記錄模塊。你甚至可以定義自定義格式,所以記錄到文件可以清除終端代碼:
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
。
在所有情況下,終端的文本都有顏色代碼,而記錄沒有。下面
出色答卷 - 這可能正是我需要的。我實際上使用日誌記錄模塊,但希望讓用戶可以選擇重定向輸出並獲取可讀文件。日誌本身是由日誌模塊創建的(並且你的方法我很可能會得到我想要的)。 – Escualo 2010-05-23 22:48:13
我剛剛測試過你的方法,它的工作原理與預期完全一致。非常感謝! – Escualo 2010-05-23 22:50:59