python简单日志类的创建

python简单日志类的创建,第1张

python简单日志类的创建

训练模型的时候,希望把训练过程中的loss,acc等指标记录到文件中以便后续查看。

class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout  #stdout
        self.file = None

    def open(self, file, mode=None):
        if mode is None: mode ='w'
        self.file = open(file, mode)

    def write(self, message, is_terminal=1, is_file=1 ):
        if 'r' in message: is_file=0

        if is_terminal == 1:
            self.terminal.write(message)
            self.terminal.flush()
            #time.sleep(1)

        if is_file == 1:
            self.file.write(message)
            self.file.flush()

    def flush(self):
        # this flush method is needed for python 3 compatibility.
        # this handles the flush command by doing nothing.
        # you might want to specify some extra behavior here.
        pass
    log.open('log.txt',mode='a')
    log.write("epoch:{}n".format(epoch))
    log.write("loss:{}n".format(loss))

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5721279.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存