我已经将所有 Python 接口用于 OSX 上的 notify/fsevents,此时我认为 python-watchdog 是最好的。Pythonic 设计,简单易用。不要与奇怪的文件系统掩码搏斗。如果您也有一个 bash 脚本,如果您感到懒惰,它会附带一个有用的 CLI 应用程序。
https://pypi.python.org/pypi/watchdog
这是我不久前整理的一个示例:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import sys
import time
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
logging.basicConfig(level=logging.DEBUG)
class MyEventHandler(FileSystemEventHandler):
def catch_all_handler(self, event):
logging.debug(event)
def on_moved(self, event):
self.catch_all_handler(event)
def on_created(self, event):
self.catch_all_handler(event)
def on_deleted(self, event):
self.catch_all_handler(event)
def on_modified(self, event):
self.catch_all_handler(event)
path = '/tmp/'
event_handler = MyEventHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()