通過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!")
在任意地方導入這個函數就可以實現了。
