Python日志無延遲實時寫入的示例
我在用python生成日志時,發(fā)現(xiàn)無論怎么flush(),文件內(nèi)容總是不能實時寫入,導致程序意外中斷時一無所獲。
以下是查到的解決方案(親測可行):
open 函數(shù)中有一個bufferin的參數(shù),默認是-1,如果設置為0是,就是無緩沖模式。 但是用二進制模式打開這個文件,并且把要寫入的信息轉(zhuǎn)換byte -like如下。 with open("test.txt",'wb',buffering=0) as f: #wb是寫模式加二進制模式 f.write(b"hello!")在字符串前加b,轉(zhuǎn)換成二進制 如果沒用二進制打開文件會提示ValueEorror: 沒把字符串轉(zhuǎn)成二進制會提示: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型的數(shù)據(jù),不可以和str相加,需要將‘\n'前加b。
(2)terminal.write函數(shù)參數(shù)需要為str類型,轉(zhuǎn)化為str。
改為:
def print(self, message): self.terminal.write(message + "\n") self.log.write(message.encode('utf-8') + b"\n")
運行成功!
以上這篇Python日志無延遲實時寫入的示例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
python新一代網(wǎng)絡請求庫之python-httpx庫操作指南
Python 的 httpx 包是一個用于 HTTP 交互的一個優(yōu)秀且靈活的模塊,下面這篇文章主要給大家介紹了關于python新一代網(wǎng)絡請求庫之python-httpx庫的相關資料,需要的朋友可以參考下2022-09-09python pandas 組內(nèi)排序、單組排序、標號的實例
下面小編就為大家分享一篇python pandas 組內(nèi)排序、單組排序、標號的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04