Mic*_*ael 6 python logging multiprocessing
根据这段代码,我创建了一个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')
Run Code Online (Sandbox Code Playgroud)
这很好用,但是当我尝试将它与使用Pool多处理功能的脚本一起使用时,我收到以下错误:
AttributeError: 'Logger' object has no attribute 'flush'
Run Code Online (Sandbox Code Playgroud)
如何修改我的Logger对象,以便它可以与任何并行运行的脚本一起使用?
eca*_*mur 22
如果要替换sys.stdout,则必须使用类似文件的对象,这意味着必须实现flush. flush可以是无操作:
def flush(self):
pass
Run Code Online (Sandbox Code Playgroud)