基于此code https://stackoverflow.com/a/5916874我创建了一个 python 对象,它既将输出打印到终端,又将输出保存到日志文件,并在其名称后附加日期和时间:
import sys
import time
class Logger(object):
"""
Creates a class that will both print and log any
output text. See https://stackoverflow.com/a/5916874
for original source code. Modified to add date and
time to end of file name.
"""
def __init__(self, filename="Default"):
self.terminal = sys.stdout
self.filename = filename + ' ' + time.strftime('%Y-%m-%d-%H-%M-%S') + '.txt'
self.log = open(self.filename, "a")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
sys.stdout = Logger('TestLog')
这很好用,但是当我尝试将它与使用Pool
多处理函数,我收到以下错误:
AttributeError: 'Logger' object has no attribute 'flush'
我该如何修改我的Logger
对象以便它可以与并行运行的任何脚本一起使用?
如果你要更换sys.stdout
,它必须带有一个类似文件的对象 http://docs.python.org/2/library/stdtypes.html#bltin-file-objects,这意味着你必须实施flush
. flush可以是空操作 http://docs.python.org/2/library/stdtypes.html#file.flush:
def flush(self):
pass
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)