多处理中的Python登录:AttributeError:'Logger'对象没有属性'flush' [英] Python logging in multiprocessing: AttributeError: 'Logger' object has no attribute 'flush'
问题描述
基于此代码,我创建了一个python对象,该对象既将输出打印到终端,又将输出保存到带有名称后面附加的日期和时间:
Based on this code I created a python object that both prints output to the terminal and saves the output to a log file with the date and time appended to its name:
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
多处理功能的脚本一起使用时,出现以下错误:
This works great, but when I try to use it with a script that uses the Pool
multiprocessing function, I get the following error:
AttributeError: 'Logger' object has no attribute 'flush'
如何修改我的Logger
对象,使其可以与任何并行运行的脚本一起使用?
How can I modify my Logger
object so that it will work with any script that runs in parallel?
推荐答案
如果要替换sys.stdout
,则必须使用 flush
可以是无操作:
If you're replacing sys.stdout
, it must be with a file-like object, which means you have to implement flush
. flush
can be a no-op:
def flush(self):
pass
这篇关于多处理中的Python登录:AttributeError:'Logger'对象没有属性'flush'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!