1 回答
TA贡献1936条经验 获得超6个赞
据我所知Watchdog,仅通知文件是否已修改,但它不会提供更改的信息,您必须自行检查。
我看到了两种显示新附加内容的方法。
首先:保持打开的文件,然后read()将只读取新内容。
我的处理程序获取文件名作为参数以在启动时打开它并始终保持打开状态。
在__init__您可以使用read()跳过现有内容
import os
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class AppendEventHandler(FileSystemEventHandler):
def __init__(self, path):
self.path = path
self.fh = open(path)
self.fh.read() # skip existing content
def on_modified(self, event):
if event.src_path == self.path:
print(self.fh.read())
if __name__ == "__main__":
event_handler = AppendEventHandler(".\\test.log")
observer = Observer()
observer.schedule(event_handler, ".", recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
第二:如果您不想保留打开的文件,那么您可以记住它的大小并fh.seek(previous_size)在附加内容开始时使用它来开始阅读。
import os
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class AppendEventHandler(FileSystemEventHandler):
def __init__(self, path):
self.path = path
self.size = os.stat(path).st_size # remeber previous size
def on_modified(self, event):
if event.src_path == self.path:
new_size = os.stat(self.path).st_size # get new size
if new_size > self.size:
fh = open(self.path)
fh.seek(self.size) # move to appended content (move to end of old content)
print(fh.read())
fh.close()
self.size = new_size # remeber new size
if __name__ == "__main__":
event_handler = AppendEventHandler("./test.log")
observer = Observer()
observer.schedule(event_handler, ".", recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
添加回答
举报