多处理中的 Python 日志记录 : AttributeError: 'Logger' object has no attribute 'flush'

标签 python logging multiprocessing

基于此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 对象,以便它可以与任何并行运行的脚本一起工作?

最佳答案

如果您要替换 sys.stdout,它必须是 file-like object ,这意味着您必须实现 flushflush can be a no-op :

def flush(self):
    pass

关于多处理中的 Python 日志记录 : AttributeError: 'Logger' object has no attribute 'flush' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20525587/

相关文章:

python - 修改函数内的给定列表

python - 将 perl 正则表达式转换为 python 正则表达式

python - 无法安装 Scrapy : "error: command ' gcc' failed with exit status 1"?

python - 打印当前日志记录级别

MySQL:慢日志;附加 CPU 使用率

python 多处理日志记录,根记录器在 windows 中不同

python - 如何定位和对齐 matplotlib 图形图例?

python - 在 python 中,在 Windows 上,如何等到鼠标移动?

java - 如何记录/跟踪java中对象的任何方法调用

python - 多处理脚本比普通脚本慢