Written with StackEdit.
watchdog是用於監控檔案事件的Python API庫。受監控的檔案事件常見的有四種,分別為:移動、新增、移除、修改。當watchdog偵測到這四個事件時,會呼叫相應的函數進行反應。
下面是官方網站上提供的範例:
import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
path = sys.argv[1] if len(sys.argv) > 1 else '.'
event_handler = LoggingEventHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
watchdog的運作流程是observer
開啟一個線程對檔案系統進行監控,當偵測到檔案事件時,將事件的旗標傳入event_handler
,由event_handler
進行反應。
在上面的範例中,由LoggingEventHandler
作為event_handler
。由LoggingEventHandler
的原碼可以看到,它繼承自FileSystemEventHandler
,並重載了FileSystemEventHandler
的on_moved
、on_created
、on_deleted
、on_modified
四個方法,並使用logging
庫進行等級為INFO
的記錄。
class LoggingEventHandler(FileSystemEventHandler):
"""Logs all the events captured."""
def on_moved(self, event):
super(LoggingEventHandler, self).on_moved(event)
what = 'directory' if event.is_directory else 'file'
logging.info("Moved %s: from %s to %s", what, event.src_path,
event.dest_path)
def on_created(self, event):
super(LoggingEventHandler, self).on_created(event)
what = 'directory' if event.is_directory else 'file'
logging.info("Created %s: %s", what, event.src_path)
def on_deleted(self, event):
super(LoggingEventHandler, self).on_deleted(event)
what = 'directory' if event.is_directory else 'file'
logging.info("Deleted %s: %s", what, event.src_path)
def on_modified(self, event):
super(LoggingEventHandler, self).on_modified(event)
what = 'directory' if event.is_directory else 'file'
logging.info("Modified %s: %s", what, event.src_path)
我們可以按照同樣的邏輯撰寫自己的event_handler
:
class MyEventHandler(FileSystemEventHandler):
"""Logs all the events captured."""
def on_created(self, event):
super(LoggingEventHandler, self).on_created(event)
what = 'directory' if event.is_directory else 'file'
logging.warning("Created %s: %s by ", what, event.src_path)
這樣就變更為在WARING
層級才會記錄新增事件,其他類別的事件都不處理。
除此之外,也可以進行其他處置,例如發現有目錄下有新增檔案後(如圖片),呼叫其他程式對其進行壓縮等等…
沒有留言:
張貼留言