import os import time import sys import io from threading import Thread class BuildLogTail(Thread): def __init__(self, fileName, logPrefix = ''): self._fileName = fileName self._logPrefix = logPrefix self._stopReading = False Thread.__init__(self) def run(self): while not self._stopReading and not os.path.exists(self._fileName): time.sleep(1) # 修复中文显示错误和 print() 报错的 'gbk' codec can't encode character sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='gb18030') with self.open_default_encoding(self._fileName, mode='r') as file: while True: where = file.tell() line = file.readline() if self._stopReading and not line: break if not line: time.sleep(1) file.seek(where) else: if sys.stdout.closed: return PrintLogASAP(self._logPrefix + line.rstrip()) def stop(self): self._stopReading = True # Wait for thread read the remaining log after process quit in 5 seconds self.join(5) @staticmethod def open_default_encoding(file, mode): return open(file, mode=mode, encoding='utf-8-sig') def PrintLogASAP(str): print(str) sys.stdout.flush() sys.stderr.flush()