watchdog使用 - python watchdog教學



python watchdog監視文件的變化 (1)

而不是LoggingEventHandler定義您的處理程序:

#!/usr/bin/python
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler


class MyHandler(FileSystemEventHandler):
    def on_modified(self, event):
        print(f'event type: {event.event_type}  path : {event.src_path}')


if __name__ == "__main__":
    event_handler = MyHandler()
    observer = Observer()
    observer.schedule(event_handler, path='/data/', recursive=False)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

修改文件或目錄時調用on_modified

伙計們,我需要查看日誌文件以進行更改。 在查看了stackoverflow問題之後,我看到人們推薦“看門狗”。 所以我正在嘗試測試,並且不確定在文件更改時添加代碼的位置:

#!/usr/bin/python
import time
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

if __name__ == "__main__":
event_handler = LoggingEventHandler()
observer = Observer()
observer.schedule(event_handler, path='.', recursive=False)
observer.start()
try:
    while True:
      time.sleep(1)
    else:
      print "got it"
except KeyboardInterrupt:
    observer.stop()
observer.join()

如果文件已被添加/更改,我在哪裡添加“得到它”,在while循環中?





watchdog