Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- import os
- import pyinotify
- import logging
- import time
- logging.basicConfig(level=logging.DEBUG)
- log = logging.getLogger(__name__)
- class EventHandler(pyinotify.ProcessEvent):
- def __init__(self, wm, targets):
- self.targets = targets
- self.wm = wm
- self.results = None
- def process_IN_CREATE(self, event):
- log.debug("recieved inotify {} event for {}".format(event.maskname, event.pathname))
- if event.pathname in self.targets:
- if event.maskname == self.targets[event.pathname]:
- self.event_triggered(event)
- def process_IN_DELETE(self, event):
- print "Removing:", event.pathname
- def event_triggered(self, event):
- if not self.results:
- self.results = []
- self.results.append(event)
- # all done?
- if len(self.results) == len(self.targets):
- self.teardown()
- def teardown(self):
- log.debug("tearing down inotify listener")
- try:
- self.wm.close()
- except OSError:
- pass
- def exists(name, timeout_secs=10, **kwargs):
- path = name
- ret = {'name': path, 'changes': {}, 'result': True, 'comment': ''}
- return ret
- if os.path.exists(path):
- msg = "path {} already exists, taking no action".format(path)
- log.debug(msg)
- ret['comment'] = msg
- return ret
- path_to_watch = os.path.dirname(path)
- mask = pyinotify.IN_CREATE | pyinotify.IN_DELETE
- wm = pyinotify.WatchManager()
- wm.add_watch(path_to_watch, mask)
- targets = {path: "IN_CREATE", "/tmp/baz": "IN_CREATE"}
- handler = EventHandler(wm, targets)
- notifier = pyinotify.Notifier(wm, handler, timeout=1000 * timeout_secs)
- log.debug("about to wait on inotify for {} seconds".format(timeout_secs))
- # block for timeout_secs while waiting for inotify events
- notifier.process_events()
- while notifier.check_events(): #loop in case more events appear while we are processing
- notifier.read_events()
- notifier.process_events()
- # check results
- if not handler.results:
- log.debug("timed out waiting for inotify event on {}".format(path))
- ret['result'] = False
- ret['comment'] = 'timed out waiting for file {}'.format(path)
- return ret
- ret['changes'] = {'created': path}
- return ret
- if __name__ == "__main__":
- print exists("/tmp/foo")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement