Wednesday, March 13, 2013

Using Pyinotify to Monitor a Directory

This example uses python and pyinotify to monitor a mount point

import os
import pyinotify as inotify

class EventHandler(inotify.ProcessEvent):
    def process_IN_CREATE(self, event):
        print "Create: %s" %  os.path.join(event.path, event.name)

    def process_IN_DELETE(self, event):
        print "Remove: %s" %  os.path.join(event.path, event.name)

wm = inotify.WatchManager()
notifier = inotify.Notifier(wm, EventHandler())
wm.add_watch('/media', inotify.IN_DELETE | inotify.IN_CREATE, rec=False)

try:
    while True:
        # process the queue of events
        notifier.process_events()
        if notifier.check_events():
            #read notified events and enqeue them
             notifier.read_events()
except KeyboardInterrupt:
    notifier.stop()

No comments:

Post a Comment