基于此code,我创建了一个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对象,使其可以与任何并行运行的脚本一起工作?
发布于 2013-12-12 01:23:37
如果您要替换sys.stdout,它必须是一个file-like object,这意味着您必须实现flush。flush can be a no-op
def flush(self):
pass发布于 2018-05-15 21:52:43
@ecatmur的答案只会修复丢失的刷新,一旦添加了这个,我就会收到:
AttributeError: 'Logger' object has no attribute 'fileno'original code的帖子中的注释提供了一个修改,它将解释任何其他缺少的属性,为了完整性,我将发布此代码的完整工作版本:
class Logger(object):
def __init__(self, filename = "logfile.log"):
self.terminal = sys.stdout
self.log = open(filename, "a")
def __getattr__(self, attr):
return getattr(self.terminal, attr)
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
pass这在Python2.7中运行是没有错误的。尚未在3.3+中测试。
发布于 2021-10-12 18:04:35
如果flush没有实现,它将不会工作,请在下面找到flush实现的详细答案。
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.terminal.write(message)
self.log.write(message)
def flush(self):
self.terminal.flush()
self.log.flush()我在没有刷新日志的情况下遇到了问题。然后,它可以按如下方式使用:
sys.stdout = Logger("file.log")https://stackoverflow.com/questions/20525587
复制相似问题