def __init__(self, paths, callback): class EventHandler(ProcessEvent): def process_IN_CREATE(self, event): # noqa callback() def process_IN_DELETE(self, event): # noqa callback() manager = WatchManager() # Watch Manager mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE # watched events self.async_notifier = AsyncNotifier(manager, EventHandler()) # aggregate inotify events try: self.async_notifier.coalesce_events() except AttributeError as inst: LOG.warn('Can not coalesce events, pyinotify does not seem to ' 'support it (maybe too old): %s' % inst) for path in paths: if os.path.exists(path): manager.add_watch(path, mask, rec=False) else: LOG.warn("%s folder doesn't exist yet." % path) wait_dir(path) manager.add_watch(path, mask, rec=False) LOG.info("%s has just been created." % path)
def entry(watch_directory, exclude): mask = IN_DELETE | IN_CREATE | IN_MODIFY | IN_CLOSE_WRITE handler = EventHandler() wm = pyinotify.WatchManager() notifier = AsyncNotifier(wm, handler) filter = ExcludeFilter(exclude) wdd = wm.add_watch( watch_directory, mask, rec=True, # 递归 auto_add=True, # 添加了新文件 新文件也会被监视 写删除那些事件 exclude_filter=filter) #notifier.loop() asyncore.loop()
def file_monitor(path='.', client=None): wm = WatchManager() mask = IN_DELETE | IN_CREATE | IN_MODIFY notifier = AsyncNotifier(wm, EventHandler(client)) wm.add_watch(path, mask, auto_add=True, rec=True) if not os.path.isfile(path): logger.debug("File %s does not exist." % path) sys.exit(3) else: logger.debug("Now starting monitor file %s." % path) global f f = open(path, 'r') st_size = os.stat(path)[6] f.seek(st_size) while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: print "keyboard Interrupt." notifier.stop() break