Python在文件和终端中的输出
有时候我希望我的程序能在终端上显示一些内容,方便我立刻查看,同时也把这些内容写到一个文件里,以便以后使用。所以我会写一些像这样的代码:
print "output"
file.write("output") #the same output as the previous line
请问,在python 2.6或2.7中,有没有其他更聪明的方法来做到这一点呢?
相关问题:
2 个回答
1
希望这还不算太晚,我来分享一下。这对我有效。
import sys
import logging
class Logger(object):
def __init__(self, filename):
self.terminal = sys.stdout
self.log = open(filename, "a")
def __getattr__(self, attr):
return getattr(self.terminal, attr)
def write(self, message):
self.log.write(message)
def flush(self):
self.log.flush()
然后,可以这样使用它
sys.stdout = Logger("file.txt")
17
你可以把这个封装成一个函数:
>>> def fprint(output):
... print output
... with open("somefile.txt", "a") as f:
... f.write("{}\n".format(output))
如果你是在记录信息,建议你看看日志模块。使用这个日志模块,你可以很方便地设置和管理多个记录信息的地方。
下面是来自日志食谱的一个例子:
import logging
# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename='/temp/myapp.log',
filemode='w')
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
# Now, we can log to the root logger, or any other logger. First the root...
logging.info('Jackdaws love my big sphinx of quartz.'
# Now, define a couple of other loggers which might represent areas in your
# application:
logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2')
logger1.debug('Quick zephyrs blow, vexing daft Jim.') # Won't print, file only
logger1.info('How quickly daft jumping zebras vex.') # Printed and to file
logger2.warning('Jail zesty vixen who grabbed pay from quack.') # Printed and to file
logger2.error('The five boxing wizards jump quickly.') # Printed and to file.
上面的例子会把所有日志级别为logging.DEBUG或更高的消息写入一个叫/temp/myapp.log的文件。级别为logging.INFO的消息则会打印到sys.stderr。我强烈推荐在需要记录信息时使用这个模块,而不仅仅是简单的调试打印。
编辑:之前的例子不对!