通过pip安装依赖
pip install watchdog
监控代码
import os
import time
import datetime
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def __init__(self):
super().__init__()
self.last_position = 0
def on_modified(self, event):
if not event.is_directory and event.src_path.endswith("log.log"):
with open(event.src_path, "r", encoding='UTF-8') as f:
f.seek(0, 2) # 将指针移动到文件末尾
if self.last_position == 0 or self.last_position > f.tell():
self.last_position = f.tell() # 如果是第一次打开文件则将读取记录移动到文件尾
f.seek(self.last_position, os.SEEK_SET) # 将指针移动到上次读取位置
try:
for line in f.readlines():
# 逐行打印文件变化内容
now = datetime.datetime.now() # 获取当前时间
print("[{}] {}".format(now.strftime("%Y-%m-%d %H:%M:%S"), line))
except UnicodeDecodeError as e:
print(e)
f.seek(0, 2) # 将指针移动到文件末尾
self.last_position = f.tell() #记录当前读取位置
if __name__ == "__main__":
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, "D:\Logs", recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()