Preface
watchdog 提供了 Python API 和 shell 工具集來監控文件系統的事件。它包含跨平台的 API,一個 shell 工具可以讓你運行命令來監控目錄的變化。以下是一個使用 watchdog 來監控目錄變化的的簡單程序,當事件發生的時候記錄日誌:
- wd_t1.py
- #!/usr/bin/env python
- import sys, os
- import time
- import logging
- from watchdog.observers import Observer
- from watchdog.events import LoggingEventHandler
- class MyEH(LoggingEventHandler):
- r''' Logs all the events captured. '''
- def __init__(self):
- super(MyEH, self).__init__()
- def on_created(self, event):
- r'''
- We only care about the file being created
- '''
- super(MyEH, self).on_created(event)
- print("This event is captured by {}:\n{}\n".format(self.__class__, event))
- STOP_SIG = 'STOP'
- 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 = MyEH()
- observer = Observer()
- observer.schedule(event_handler, path, recursive=True)
- observer.start()
- try:
- while True:
- time.sleep(1)
- if os.path.isfile(STOP_SIG):
- print("Receive STOP signal({})...".format(STOP_SIG))
- os.remove(STOP_SIG)
- observer.stop()
- break;
- except KeyboardInterrupt:
- observer.stop()
- observer.join()
watchdog 包含一個實用的腳本,名為 watch demo。使用 watchmedo --help 命令可以查看更多關於這個腳本的信息。
以下是一個監控 *.py 和 *.txt 文件的變化,記錄到日誌而忽略其他目錄中文件變化的腳本:
- watchmedo log \
- --patterns="*.py;*.txt" \
- --ignore-directories \
- --recursive \
- .
- watchmedo shell-command \
- --patterns="*.py;*.txt" \
- --recursive \
- --command='echo "${watch_src_path}"' \
- .
Supplement
* Watchdog document
沒有留言:
張貼留言