【Python】Python日志无延迟实时写入


我在用python生成日志时,发现无论怎么flush(),文件内容总是不能实时写入,导致程序意外中断时一无所获。

以下是查到的解决方案(亲测可行):


open 函数中有一个bufferin的参数,默认是-1,如果设置为0是,就是无缓冲模式。 
但是用二进制模式打开这个文件,并且把要写入的信息转换byte -like如下。

with open("test.txt",'wb',buffering=0) as f:
#wb是写模式加二进制模式
    f.write(b"hello!")在字符串前加b,转换成二进制

如果没用二进制打开文件会提示ValueEorror:

没把字符串转成二进制会提示:TypeError: a bytes-like object is required, not ‘str’

测试:


class Logger(object):
    def __init__(self, log_path="default.log"):
        self.terminal = sys.stdout
        # self.log = open(log_path, "w+")
        self.log = open(log_path, "wb", buffering=0)

    def print(self, message):
        self.terminal.write(message + "\n")
        self.log.write(message.encode('utf-8') + b"\n")

    def flush(self):
        self.terminal.flush()
        self.log.flush()

    def close(self):
        self.log.close()

报错1:TypeError: can't concat str to bytes

报错2:write需要str对象,无法写入bytes对象(大意)

这是因为:

(1)log.write需要写入bytes对象,这里没问题。但是encode返回的是bytes型的数据,不可以和str相加,需要将‘\n’前加b。

(2)terminal.write函数参数需要为str类型,转化为str。

改为:


    def print(self, message):
        self.terminal.write(message + "\n")
        self.log.write(message.encode('utf-8') + b"\n")

运行成功!

来源:https://blog.csdn.net/ztf312/article/details/85157572


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM