请选择 进入手机版 | 继续访问电脑版
MSIPO技术圈 首页 IT技术 查看内容

python3 将print打印的内容保存到日志

2023-07-13

当你在Python中使用print函数时,通常会将输出显示在控制台上。但是,有时你可能希望将输出写入日志文件中,以便稍后进行查看和分析,而不需要每一次都要重新运行一下程序。

为了实现这个目的,可以编写一个函数,该函数将重定向print语句到日志文件中。以下是实现此功能的Python代码:

def make_print_to_file(path='./'):
    '''
    A function to redirect print statements to a log file.

    :param path: The path to the directory where the log file should be saved.
    :return: None
    '''
    import sys
    import os
    import datetime
 
    class Logger(object):
        def __init__(self, filename="Default.log", path="./"):
            '''
            :param filename: The name of the log file to be created.
            :param path: The path to the directory where the log file should be saved.
            '''
            self.terminal = sys.stdout # terminal是标准输出,即print函数输出的位置
            self.path= os.path.join(path, filename) # path是文件保存的路径
            self.log_file = open(self.path, "a", encoding='utf8',) # log_file是文件对象,用于写入文件
            print("Saving logs to:", os.path.join(self.path, filename)) # 打印日志保存的路径
 
        def write(self, message):
            '''
            Writes the message to both the terminal and the log file.

            :param message: The message to be written.
            '''
            self.terminal.write(message) # 将message写入到terminal,即标准输出
            self.log_file.write(message) # 将message写入到log_file,即文件
            self.log_file.flush() # 刷新缓存区,即将缓存区的内容写入到文件(这个地方一定要刷新,不然的话,文件中会没有内容)
 
        def flush(self):
            pass
 
    # Create a new log file with the current date as the filename
    fileName = datetime.datetime.now().strftime('day'+'%Y_%m_%d')
    sys.stdout = Logger(fileName + '.log', path=path)
 
    # Print a header to indicate that all subsequent print statements will be logged
    print("Logging started for:", fileName.center(60,'*'))

    # Return the logger object
    return sys.stdout.log_file
 
if __name__ == '__main__':
    # Redirect print statements to a log file
    log_file = make_print_to_file(path='./')
 
    # Any print statements after this point will be logged to the file
    print("1234124")
    print("--")
 
    # Close the log file
    log_file.close()

相关阅读

热门文章

    手机版|MSIPO技术圈 皖ICP备19022944号-2

    Copyright © 2024, msipo.com

    返回顶部