加入收藏 | 设为首页 | 会员中心 | 我要投稿 阜阳站长网 (https://www.0558zz.com/)- 科技、建站、内容创作、云计算、网络安全!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-07-09 07:56:43 所属栏目:Python 来源:互联网
导读:我在用python生成日志时,发现无论怎么flush(),文件内容总是不能实时写入,导致程序意外中断时一无所获。

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

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

<pre class="has">
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’

测试:

<pre class="has">
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。

改为:

<pre class="has">
def print(self,message):
self.terminal.write(message + "n")
self.log.write(message.encode('utf-8') + b"n")

运行成功!

(编辑:阜阳站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读