【Python】Python日志无延迟实时写入
我在用python生成日志时,发现无论怎么flush(),文件内容总是不能实时写入,导致程序意外中断时一无所获。 以下是查到的解决方案(亲测可行): <pre class="has"> with open("test.txt",'wb',buffering=0) as f: wb是写模式加二进制模式
如果没用二进制打开文件会提示ValueEorror: 没把字符串转成二进制会提示:TypeError: a bytes-like object is required,not ‘str’ 测试: <pre class="has"> self.log = open(log_path,"w+")
报错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"> 运行成功! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |