python中的print信息写入文件

调试code中,在循环体经常需要将当前epoch的信息print出来进行校验。当epoch过多时难以查阅,因此我们将print内容输出到文件中保存。

一、demo练习

sys.out对象默认为当前屏幕输出,可以通过变量改为文件写入,同样也可以重新指定回当前屏幕,代码如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
"""
write the infos of print to files
author:huangrui
"""

import sys
print("hello, i come first!")

__console = sys.stdout   # 用于后期还原,将当前屏幕输出对象进行保存

# 把打印重定向至文件
f=open('outfile.log',"a+")
sys.stdout=f
print('write file~~~')

# 打印重定向至屏幕
sys.stdout = __console
print("im coming back!")

打印结果:

文件写入结果:

二、应用封装

将print 信息打印在屏幕的同时写入文档,进行封装。文件名命名为当前时间.log。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""
write the infos of print to files
author:huangrui
"""
import os
import sys
import io
import datetime
from tqdm import tqdm
import time

def create_detail_day():
    '''
    :return:
    '''
    # 年_月_日
    daytime = datetime.datetime.now().strftime('day'+'%Y_%m_%d')
    # 时:分:秒
    hourtime = datetime.datetime.now().strftime("%H_%M_%S")
    detail_time = daytime + "__" + hourtime
    return detail_time

def make_print_to_file(path='./'):
    '''
    example:
    use make_print_to_file() , and the all the information of funtion print , will be write in to a log file
    :param path: the path to save print information
    :return:
    '''
    class Logger(object):
        def __init__(self, filename="Default.log", path="./"):
            sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
            self.terminal = sys.stdout
            self.log = open(os.path.join(path, filename), "a", encoding='utf8')
        def write(self, message):
            self.terminal.write(message)
            self.log.write(message)
        def flush(self):
            pass
    sys.stdout = Logger(create_detail_day() + '.log', path=path)
    print(create_detail_day().center(60,'*'))

if __name__ == '__main__':
    make_print_to_file(path="log/")
    print('explanation'.center(80, '*'))
    info1 = '从大到小排序'
    info2 = ' sort the form large to small'
    print(info1)
    print(info2)
    for i in tqdm(range(10)):
        time.sleep(1)
        print(i)
    print('END: explanation'.center(80, '*'))

log写入结果: