2012-09-26 21 views
1

我想登錄到一個文本文件,無論是print編輯sys.stdout。雖然我明白聰明的人能拿出更優雅和Python的解決方案,這是我的解決方案如何用導入語句覆蓋python builtins?

class logger: 

    def __init__(self, filename='log.txt'): 
    self.logf = open(filename, 'a') 

    global print 
    self.__print = print 

    print = self.lognprint 

    def __del__(self): 
    self.logf.close() 

    def lognprint(self, *args, **keywords): 
    self.__print(*args, file = self.logf, **keywords) 
    self.__print(*args, **keywords) 

現在如果在我的代碼的任何地方我想補充

mylog = logger() 

東西都print ED事後也記錄。

但很多明顯的原因,這是不是安全/良好。例如多個logger對象可能是討厭的。

另外我對

from __future__ import print_function 

啓發(見this例如),我想要做類似的事情,所以,當我import我的模塊,內建print是我的版本打印的任何地方覆蓋在代碼中。

這怎麼可能?

+0

請告訴我你用這個來記錄你不能**改變的第三方程序的'print'輸出。如果不是(==如果它是你自己的使用'print'的代碼):改變它使用[logging](http://docs.python.org/library/logging.html)模塊。 –

+3

您總是可以通過'__builtins __。print'引用內置的打印功能。無需在新變量中捕獲它。 –

+0

@LukasGraf'我正在使用它來從第三方程序'打印'輸出,我**不能**改變',_tell我你想聽到什麼_ –

回答

1

而不是把你的代碼放在類中,把它放在模塊級別。這種方式,將被第一次導入模塊執行:

# logging.py 
print = my_print 
1

類似的解決方案,或記錄的東西到一個文件,該文件也印到std.out,在logging cookbook給出。
這裏是你如何可以簡單地記錄的東西到名爲「spam.log」,同時也文件打印某些東西std.out:

import logging 

logger = logging.getLogger('simple_example') 
logger.setLevel(logging.DEBUG) 
# create file handler which logs even debug messages 
fh = logging.FileHandler('spam.log') 
fh.setLevel(logging.DEBUG) 
# create console handler with a higher log level 
ch = logging.StreamHandler() 
ch.setLevel(logging.ERROR) 
# create formatter and add it to the handlers 
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 
ch.setFormatter(formatter) 
fh.setFormatter(formatter) 
# add the handlers to logger 
logger.addHandler(ch) 
logger.addHandler(fh) 

# 'application' code 
logger.debug('debug message') 
logger.info('info message') 
logger.warn('warn message') 
logger.error('error message') 
logger.critical('critical message') 

在這個例子中的所有郵件轉到文件,只有更高的水平去控制檯。