Вот простой менеджер по контексту, который печатает к консоли и пишет тот же вывод в файл. Это также пишет любые исключения в файл.
import traceback
import sys
# Context manager that copies stdout and any exceptions to a log file
class Tee(object):
def __init__(self, filename):
self.file = open(filename, 'w')
self.stdout = sys.stdout
def __enter__(self):
sys.stdout = self
def __exit__(self, exc_type, exc_value, tb):
sys.stdout = self.stdout
if exc_type is not None:
self.file.write(traceback.format_exc())
self.file.close()
def write(self, data):
self.file.write(data)
self.stdout.write(data)
def flush(self):
self.file.flush()
self.stdout.flush()
Для использования менеджера по контексту:
print("Print")
with Tee('test.txt'):
print("Print+Write")
raise Exception("Test")
print("Print")
Я попробовал несколько решений здесь и не нашел то, которое пишет в файл и в консоль одновременно. Таким образом, вот то, что я сделал (на основе этого ответа)
class Logger(object):
def __init__(self):
self.terminal = sys.stdout
def write(self, message):
with open ("logfile.log", "a", encoding = 'utf-8') as self.log:
self.log.write(message)
self.terminal.write(message)
def flush(self):
#this flush method is needed for python 3 compatibility.
#this handles the flush command by doing nothing.
#you might want to specify some extra behavior here.
pass
sys.stdout = Logger()
, Это решение использует больше вычислительной мощности, но надежно сохраняет все данные из stdout в файл регистратора и использует меньше memeory. Для моих потребностей я добавил время штамп в self.log.write (сообщение) также. Работает отлично.