python的文件监控模块主要有两种,分别为pyinotify和watchdog。其中pyinotify只支持linux,而watchdog支持跨平台。

安装

使用pip安装

pip install pyinotify
pip install watchdog

快速开始

pyinotify项目地址:https://github.com/seb-m/pyinotify 由于pyinotify不支持mac,所以没有深入研究。下面是一个简单的实例。

import pyinotify

class EventHandler(pyinotify.ProcessEvent):

    def process_IN_CREATE(self, event):
        print('create:', event.pathname)

    def process_IN_DELETE(self, event):
        print('delete:', event.pathname)

    def process_IN_MODIFY(self, event):
        print('modify:', event.pathname)

if __name__ == "__main__":
    wm = pyinotify.WatchManager()
    mask = pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_MODIFY
    notifier = pyinotify.Notifier(wm, EventHandler())
    wm.add_watch("./", mask, rec=True, auto_add=True)
    notifier.loop()

watchdog项目地址:https://github.com/gorakhargosh/watchdog 这里写了一个简单的MyHandler类,对不同的监控信息进行打印。

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class MyHandler(FileSystemEventHandler):   

    def on_modified(self, event):
        print("log file %s modeified!" % event.src_path)

    def on_moved(self, event):
        print("log file %s moved!" % event)

    def on_created(self, event):
        print("log file %s created!" % event.src_path)

    def on_deleted(self, event):
        print("log file %s deleted!" % event.src_path)


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

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