在Python开发中,将终端输出保存到文件是常见需求,除了手动逐行写入文件外,重定向sys.stdout是更高效的方式,能够一次性捕获所有标准输出内容并写入指定文件。

sys.stdout的基本作用
sys.stdout是Python标准库sys模块中的标准输出流对象,默认情况下指向终端控制台,所有print函数输出的内容都会写入这个流。通过修改sys.stdout的指向,就可以改变输出的目标位置。
基础重定向实现方法
我们可以通过自定义一个类,实现write方法,将其赋值给sys.stdout,从而实现输出重定向。以下是一个简单的示例:
import sys
class OutputRedirector:
def __init__(self, file_path):
# 打开目标文件,以追加模式写入,编码设置为utf-8避免中文乱码
self.file = open(file_path, 'a', encoding='utf-8')
def write(self, content):
# 将内容写入文件
self.file.write(content)
# 同时刷新缓冲区,确保内容及时写入
self.file.flush()
def close(self):
# 关闭文件
self.file.close()
# 原始输出内容
print("这是第一行终端输出")
print("这是第二行终端输出")
# 重定向sys.stdout到文件
sys.stdout = OutputRedirector("output.log")
# 重定向后的输出会写入文件
print("这行内容会保存到output.log文件中")
print("第二行保存到文件的内容")
# 恢复原来的sys.stdout(指向终端)
sys.stdout.close()
sys.stdout = sys.__stdout__
# 恢复后输出回到终端
print("这行内容会显示在终端上")
更灵活的重定向方案
如果需要在输出到文件的同时,仍然在终端显示内容,可以修改自定义类的write方法,同时写入文件和终端:
import sys
class DualOutputRedirector:
def __init__(self, file_path):
self.file = open(file_path, 'a', encoding='utf-8')
# 保存原始的sys.stdout引用
self.original_stdout = sys.__stdout__
def write(self, content):
# 同时写入文件和原始终端
self.file.write(content)
self.original_stdout.write(content)
self.file.flush()
def close(self):
self.file.close()
# 使用双重输出重定向
sys.stdout = DualOutputRedirector("dual_output.log")
print("这行内容会同时显示在终端和dual_output.log文件中")
print("第二行双重输出的内容")
# 恢复配置
sys.stdout.close()
sys.stdout = sys.__stdout__
print("恢复终端输出后的内容")
注意事项
- 重定向sys.stdout后,所有的print输出、以及直接调用sys.stdout.write的内容都会被捕获,需要注意不要遗漏恢复原始配置,否则后续所有输出都会导向文件。
- 自定义类的write方法需要接收字符串参数,并且不需要返回值,否则可能会触发异常。
- 如果程序运行过程中出现异常,可能导致sys.stdout没有正确恢复,建议在finally代码块中处理恢复逻辑。
- 打开文件时建议指定编码格式,避免中文输出出现乱码问题。
使用上下文管理器优化
为了避免忘记恢复sys.stdout,可以将其封装为上下文管理器,自动处理重定向和恢复逻辑:
import sys
class StdoutRedirector:
def __init__(self, file_path):
self.file_path = file_path
self.original_stdout = None
self.file = None
def __enter__(self):
self.original_stdout = sys.stdout
self.file = open(self.file_path, 'a', encoding='utf-8')
sys.stdout = self.file
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout = self.original_stdout
if self.file:
self.file.close()
# 使用上下文管理器
with StdoutRedirector("context_output.log"):
print("上下文管理器内的输出保存到文件")
print("第二行上下文输出内容")
print("上下文管理器外的输出回到终端")
这种方式不需要手动恢复sys.stdout,即使代码块内出现异常,也会自动恢复原始输出配置,更加安全可靠。
Pythonsys_stdout终端输出保存文件重定向修改时间:2026-06-09 20:42:27