import builtins
import sys
# 保存原始的print函数
original_print = print
# 重写print函数
def new_print(*args, **kwargs):
# 调用原始print函数输出到控制台
original_print(*args, **kwargs)
# 同时输出到文件(如果文件已打开)
if hasattr(new_print, 'log_file') and new_print.log_file:
# 确保文件参数不被传递给原始print两次
file_kwargs = kwargs.copy()
file_kwargs['file'] = new_print.log_file
original_print(*args, **file_kwargs)
new_print.log_file.flush() # 确保内容立即写入文件
# 替换内置的print函数
builtins.print = new_print
# 使用示例
def setup_logging(filename):
"""设置日志文件"""
new_print.log_file = open(filename, 'w', encoding='utf-8')
def close_logging():
"""关闭日志文件"""
if hasattr(new_print, 'log_file') and new_print.log_file:
new_print.log_file.close()
new_print.log_file = None
# 设置日志文件
setup_logging('output.txt')
# # 关闭日志文件
# close_logging()
# # 恢复原始print函数(可选)
# builtins.print = original_print