【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