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

该文章提供了一个Python函数,该函数将print语句的输出重定向到日志文件,便于后期查看和分析。通过创建一个名为Logger的类,实现了同时向终端和日志文件写入的功能。用户可以指定日志保存的路径和文件名,所有后续的print语句都将被记录到指定的日志文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当你在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()
### 如何用 Python 将 `print` 输出保存到文本文件 (TXT) 在 Python 中,可以通过多种方式将 `print` 的输出保存到 `.txt` 文件中。以下是几种常见的方法及其具体实现: #### 方法一:使用 `with open()` 和重定向标准输出 可以利用 `sys.stdout` 来重新定义默认的标准输出流,从而将原本打印到控制台的内容改写至指定的 `.txt` 文件。 ```python import sys output_file = "output.txt" # 使用上下文管理器打开目标文件并设置为只写模式 ('w') with open(output_file, 'w') as f: # 临时更改标准输出为目标文件对象 original_stdout = sys.stdout sys.stdout = f # 正常调用 print 函数即可完成向文件中的写入操作 print("这是第一行数据") print("这是第二行数据") # 恢复原始标准输出配置 sys.stdout = original_stdout ``` 这种方法简单直观,在实际应用过程中非常方便[^3]。 #### 方法二:直接修改 `print` 函数的目标参数 除了改变全局范围内的标准输出外,还可以针对单次调用单独设定其输出位置。这通过传递额外的关键字参数 `file=` 实现。 ```python output_file_path = "./example/output.txt" with open(output_file_path, 'a') as file_handler: # 追加模式('a'), 或者覆盖模式('w') print("这条消息会被追加到文件里", file=file_handler) ``` 上述代码片段展示了如何不干扰其他部分正常运行的同时仅把特定的信息存储下来[^1]。 #### 方法三:创建自定义日志处理器类 对于更复杂的需求场景,则可能需要构建专门用于处理此类任务的对象结构。下面给出了一种基于类的设计方案示例: ```python class LoggingOutput: def __init__(self,filename): self.filename=filename def write(self,text): with open(self.filename,'a')as logf: logf.write(text+'\n') captured_logger=LoggingOutput('log_output.txt') original_print=print def logged_print(*args,**kwargs): captured_text=' '.join(map(str,args)) if kwargs.get('end','\n') != '\n': captured_text += repr(kwargs['end']) del kwargs['end'] original_print(captured_text,file=captured_logger,*args,**kwargs) logged_print("测试一下新功能") ``` 此版本允许我们更加灵活地定制行为逻辑,并且保持原有接口不变以便兼容现有代码库[^5]。 综上所述,无论你是初学者还是高级开发者都可以找到适合自己项目需求的最佳实践解决方案来解决这个问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值