[英]Python Multiprocessing: AttributeError: 'Test' object has no attribute 'get_type'
[英]Python logging in multiprocessing: AttributeError: 'Logger' object has no attribute 'flush'
基於此代碼,我創建了一個 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
,它必須是一個類文件對象 ,這意味着你必須實現flush
。 flush
可以是no-op :
def flush(self):
pass
@ ecatmur的答案只會修復丟失的同花順,一旦添加了我收到:
AttributeError: 'Logger' object has no attribute 'fileno'
原始代碼的帖子中的注釋提供了一個修改,它將解釋任何其他缺少的屬性,為了完整性,我將發布此代碼的完整工作版本:
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
這在Python 2.7中沒有錯誤地運行。 尚未在3.3+中測試過。
如果未實現刷新,它將不起作用,請在下面找到已實現刷新的詳細答案。
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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.