我的博客

python 同时向屏幕(stdout)和文件输出的方法

目录

以前知道有 tee 命令可以在实现,但是用的很少。

而且我的需求是,最近在 Jupyter Notebook 中执行脚本,需要关掉文件以后仍能看到期间的输出。

我自己的实现是写一个 log 函数代替 print,今天读到一个别人的方法。(代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import os
import sys

run_log_counter = 0

while(os.path.exists(args.folder + '/run_{}.log'.format(run_log_counter))):
run_log_counter += 1

file_log = open(args.folder + '/run_{}.log'.format(run_log_counter),'w') # File where you need to keep the logs
file_log.write("")
class Unbuffered:
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
file_log.write(data) # Write the data of stdout here to a text file as well
def flush(self):
pass

sys.stdout = Unbuffered(sys.stdout)

这样 print 的结果都会被写入到文件里了。

评论无需登录,可以匿名,欢迎评论!