python-将print内容保存到文件的3种方式

通过sys.stdout得到print输出的内容,再进行保存

方式一: 一次运行

import sys


class Logger(object):
    def __init__(self, file_path: str = "./Default.log"):
        self.terminal = sys.stdout
        self.log = open(file_path, "a", encoding="utf-8")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

    def flush(self):
        pass


if __name__ == '__main__':
    sys.stdout = Logger('./log.txt')
    print('hello world!')

这种方法只需要运行一次,之后就可以直接使用print函数来保存内容,但如果程序中途出错可能出现部分内容丢失。

方式二: 多一个步骤

import sys


class PrintToFile(object):
    def __init__(self, file_path: str = "./Default.log"):
        self.file_path = file_path
        self.original_stdout = sys.stdout

    def __enter__(self):
        self.file = open(self.file_path, 'a', encoding="utf-8")
        sys.stdout = self.file
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        sys.stdout = self.original_stdout
        self.file.close()


if __name__ == '__main__':
    with PrintToFile('./log.txt'):
        print("Hello, world!")

这种方式可以及时保存内容,但要把print写在with的作用域内。

方式三: 重写print函数

# 保存原始的 print 函数
rewrite_print = print
# 定义新的 print 函数
def print(*arg):
    file_path = './log.txt'
    # 打印到控制台
    rewrite_print(*arg)
    # 保存到文件
    rewrite_print(*arg, file=open(file_path, "a", encoding="utf-8"))


if __name__ == '__main__':
    print("Hello, world!")

在任意地方导入这个函数就可以实现了。

posted @ 2022-03-15 10:55  漫漫长夜何时休  阅读(3288)  评论(0编辑  收藏  举报