import sys
from contextlib import redirect_stdout
class DoubleWrite:
...
with open('my_log.log', 'w') as logfile:
with redirect_stdout(DoubleWrite(sys.stdout, logfile)):
print('test')
def echo(file):
with open(file, 'w') as log:
while True:
text = yield
log.write(text + '\n')
print(text)
e = echo('log.txt')
next(e)
e.send('123')
e.send('456')
作为一个从字面上执行问题中提出的任务的下意识的解决方案:您可以创建一个接受两个文件对象的类,并且在写入此类的对象时,写入两个文件对象。
通常,建议使用现有的日志记录解决方案,尤其是
logging.更新。
为了在 Python 3 中正确重定向和后续恢复
sys.stdout,最好使用上下文管理器contextlib.redirect_stdout。不幸的是,Python 2 标准库中没有这样的上下文管理器。使用示例(对于 Python 3):
退出区块后,该
with redirect_stdout(...)值将被sys.stdout恢复。使用模块
logging:您可以通过指定 Formatter 来自定义输出格式
'[%(asctime)s] %(filename)s:%(lineno)d %(levelname)-8s %(message)s'并获取以下字符串:代理对列表全部内容的调用