Python通过重写sys.stdout将控制台日志重定向到文件

Python通过重写sys.stdout将控制台日志重定向到文件

class Logger(object):
    def __init__(self,fileN ="Default.log"):
        self.terminal = sys.stdout
        self.log = open(fileN,"a")
 
    def write(self,message):
        self.terminal.write(message)
        self.log.write(message)
 
    def flush(self):
        pass
 
sys.stdout = Logger("D:\\1.txt") #这里我将Log输出到D盘
#下面所有的方法,只要控制台输出,都将写入"D:\\1.txt"
print(“sdfghjkl”)

https://www.cnblogs.com/buergege520/p/8548037.html

https://www.cnblogs.com/turtle-fly/p/3280519.html

原文地址:https://www.cnblogs.com/lazysang/p/15481191.html