Python 上下文管理器:print输出的时候同时保存到文件中

import sys

class print_and_save(object):
    def __init__(self, filepath):
        self.f = open(filepath, 'w')

    def __enter__(self):
        self.old=sys.stdout #将当前系统输出储存到临时变量
        sys.stdout=self
    
    def write(self, message):
        self.old.write(message)
        self.f.write(message)

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.f.close()
        sys.stdout=self.old


with print_and_save("a.txt"):
    print("Hello world")

# 输出:Hello world
# 文件a.txt 内容也写入了 Hello world

猜你喜欢

转载自www.cnblogs.com/JohnRain/p/10089419.html