Skip to content

Instantly share code, notes, and snippets.

@yangg

yangg/filewatcher.py

Last active Dec 16, 2015
Embed
What would you like to do?
Monitoring filesystems events with inotify
#!/usr/bin/env python
# coding: utf-8
# https://github.com/seb-m/pyinotify
from pyinotify import WatchManager, Notifier, ProcessEvent, IN_CREATE, IN_MODIFY, IN_DELETE
import os, sys
class FileHandler(ProcessEvent):
def process_IN_CREATE(self, event):
print "create file: %s " % os.path.join(event.path, event.name)
def process_IN_MODIFY(self, event):
print "Modify file: %s " % os.path.join(event.path, event.name)
def process_IN_DELETE(self, event):
print "Delete file: %s " % os.path.join(event.path, event.name)
def watcher(path = None):
path = path or '.'
manager = WatchManager()
manager.add_watch(path, IN_CREATE | IN_MODIFY | IN_DELETE, rec = True)
notifier = Notifier(manager, FileHandler())
print 'File watcher start at "%s" ...' % path
while True:
try:
notifier.process_events()
if notifier.check_events():
notifier.read_events()
except KeyboardInterrupt:
notifier.stop()
break
if __name__ == "__main__":
watcher(len(sys.argv) > 1 and sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment