python将控制台输出保存到文件

在平时工作中,有时我们需要将控制台输出保存到文件

1.命令行用>覆盖写入和>>追加写入

for i in range(10000):
    print(i)
View Code
#将控制台输出覆盖写入到文件

python myprint.py > myprint.txt

#将控制台输出追加写入到文件

python myprint.py >> myprint.txt

2.将sys.stdout输出到文件

复制代码
import sys
import time
f=open("myprint.txt","w+")
sys.stdout=f
for i in range(1000):
    print(i*9)
View Code
复制代码

缺点:只能保存到文件,但控制台无输出

3.利用print函数中的file参数

复制代码
import sys
import time
f=open("myprint.txt","w+")
for i in range(100):
    print("--{}--".format(i**2),file=f,flush=True)
    print("--{}--".format(i ** 2),file=sys.stdout)
    time.sleep(0.5)
View Code
复制代码

将控制台输出的同时即时保存到文件

print函数中的file参数,file=f,输出到文件;file=sys.stdout,输出到终端;flush=True,即时刷新

4.用类实现

复制代码
import sys
class Logger(object):
    def __init__(self, filename='default.log', stream=sys.stdout):
        self.terminal = stream
        self.log = open(filename, 'a')

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

    def flush(self):
        pass

sys.stdout = Logger(stream=sys.stdout)

# now it works
print('print something')
print("output")
View Code
复制代码

 

posted @   腹肌猿  阅读(12738)  评论(1编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示