Python print输出重定向到文件和屏幕,超简单

2020-06-12 09:39:49 浏览数 (1)

代码语言:javascript复制
import sys
import os
 
class Logger(object):
    def __init__(self, filename="log.txt"):
        self.terminal = sys.stdout
        self.log = open(filename, "a")
 
    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)
 
    def flush(self):
        pass

path = os.path.abspath(os.path.dirname(__file__))
type = sys.getfilesystemencoding()
sys.stdout = Logger()
print(453453)
print(path)
print(type)

0 人点赞