def _reloader_inotify(fnames, interval=None): #: Mutated by inotify loop when changes occur. changed = [False] # Setup inotify watches from pyinotify import WatchManager, EventsCodes, Notifier wm = WatchManager() mask = "IN_DELETE_SELF IN_MOVE_SELF IN_MODIFY IN_ATTRIB".split() mask = reduce(lambda m, a: m | getattr(EventsCodes, a), mask, 0) def signal_changed(event): if changed[0]: return _log('info', ' * Detected change in %r, reloading' % event.path) changed[:] = [True] for fname in fnames: wm.add_watch(fname, mask, signal_changed) # ... And now we wait... notif = Notifier(wm) try: while not changed[0]: notif.process_events() if notif.check_events(timeout=interval): notif.read_events() # TODO Set timeout to something small and check parent liveliness finally: notif.stop() sys.exit(3)
def main(): argparser = argparse.ArgumentParser(description='%(prog)s watches directory for auction/* files to attach esnipers.') argparser.add_argument('--version', action='version', version='%(prog)s 0.3') argparser.add_argument('-d', '--debug', action='store_true', help='print simple debug statements') argparser.add_argument('directory', help='Directory to watch for auctions.') args = argparser.parse_args() if args.debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) os.chdir(args.directory) snipers = Snipers() wm = WatchManager() mask = EventsCodes.ALL_FLAGS['IN_CLOSE_WRITE']|EventsCodes.ALL_FLAGS['IN_MOVED_TO']| \ EventsCodes.ALL_FLAGS['IN_MOVED_FROM']|EventsCodes.ALL_FLAGS['IN_DELETE'] notifier = Notifier(wm, ProcessFiles(snipers)) wm.add_watch('auction/', mask) auctions = filter(filefilter, os.listdir('auction/')) for a in auctions: snipers.restart(a) while True: logging.debug('cycle') if notifier.check_events(None): # "None" necessary for endless select() notifier.read_events() notifier.process_events()
class TrackState(State, ProcessEvent): mask = (EventsCodes.OP_FLAGS['IN_DELETE'] | EventsCodes.OP_FLAGS['IN_CLOSE_WRITE']) def __init__(self, *args, **kwargs): State.__init__(self, *args, **kwargs) self.wm = WatchManager() self.notifier = Notifier(self.wm, self) def process_IN_CLOSE_WRITE(self, event): debug("IN_CLOSE_WRITE: %r" % (event,)) path = os.path.join(event.path, event.name) if os.path.isfile(path) and self.acceptable(path): self.upload(self.filename_to_File(path)) def process_IN_DELETE(self, event): debug("IN_DELETE: %r" % (event,)) path = os.path.join(event.path, event.name) if self.acceptable(path): self.delete(self.filename_to_File(path)) def run(self): for f in self.files: f = os.path.abspath(f) self.wm.add_watch(f, self.mask, rec=True, auto_add=True) try: while True: self.notifier.process_events() if self.notifier.check_events(100): self.notifier.read_events() sleep(0) except KeyboardInterrupt: self.notifier.stop()
class Watcher(object): def __init__(self, incoming_path, logger=None): self.incoming_path = incoming_path self.logger = logger or logging.getLogger('Watcher') self.wm = WatchManager() mask = IN_CLOSE_WRITE # watched events self.event_processor = WatcherProcesEvent(logger=self.logger) self.notifier = Notifier(self.wm, self.event_processor) wdd = self.wm.add_watch(self.incoming_path, mask, rec=True) def loop(self): """ Check for inotify events and process then when found. Note, check_events() below is blocking and the loop will not complete until an event that is being listened for occurs. """ if self.notifier.check_events(): # read notified events and enqeue them self.notifier.read_events() # process the queue of events self.notifier.process_events() def stop(self): # destroy the inotify's instance on this interrupt (stop monitoring) self.notifier.stop()
class LinuxFileSysMonitor(FileSysMonitor): """File system monitor thread""" def __init__(self, name=None): super(LinuxFileSysMonitor, self).__init__(name) self.defaultMask = IN_DELETE | IN_CREATE | IN_MODIFY | IN_MOVED_TO | IN_MOVED_FROM self.wm = WatchManager() self.__lock = threading.Lock() def addWatch(self, path, mask=None): """Add watch for path""" super(LinuxFileSysMonitor, self).addWatch(path, mask) if not mask: mask = self.defaultMask self.wm.add_watch(path, mask, auto_add=True, rec=True) def run(self): """Thread entry""" super(LinuxFileSysMonitor, self).run() self.notifier = Notifier(self.wm, EventHandler(None, fsMonitor = self)) while not self.threadStop: self.processMsg(1) if self.notifier.check_events(1000): self.notifier.read_events() self.notifier.process_events() def stop(self): """Stop watch""" super(LinuxFileSysMonitor, self).stop() self.notifier.stop()
class QNotifier(QThread): def __init__(self, wm, processor): self.event_queue = list() self._processor = processor self.notifier = Notifier(wm, NinjaProcessEvent(self.event_queue.append)) self.notifier.coalesce_events(True) self.keep_running = True QThread.__init__(self) def run(self): while self.keep_running: try: self.notifier.process_events() except OSError: pass # OSError: [Errno 2] No such file or directory happens e_dict = {} while len(self.event_queue): e_type, e_path = self.event_queue.pop(0) e_dict.setdefault(e_path, []).append(e_type) keys = list(e_dict.keys()) while len(keys): key = keys.pop(0) event = e_dict.pop(key) if (ADDED in event) and (DELETED in event): event = [e for e in event if e not in (ADDED, DELETED)] for each_event in event: self._processor(each_event, key) if self.notifier.check_events(): self.notifier.read_events() self.notifier.stop()
def run(self, location='.'): transport = get_transport(location) root = transport.local_abspath('.') new_dirs = set('.') relpaths = set('.') while relpaths: relpath = relpaths.pop() paths = transport.list_dir(relpath) for path in paths: st = transport.stat(relpath + '/' + path) if S_ISDIR(st.st_mode): if path != '.bzr': new_dirs.add(relpath + '/' + path) relpaths.add(relpath + '/' + path) # gather all dirs wm = WatchManager() added_flag = False handler = ProcessClose() handler._bzr_wm = wm notifier = Notifier(wm, handler) # read and process events try: while True: if new_dirs: for path in new_dirs: wm.add_watch(root + '/' + path, dir_mask) new_dirs = set() notifier.process_events() if notifier.check_events(): notifier.read_events() finally: notifier.stop()
def run(self): self.pclose = PClose(self.path) PC = self.pclose # only watch these events mask = IN_CLOSE_WRITE | IN_CLOSE_NOWRITE # watch manager instance wm = WatchManager() notifier = Notifier(wm, PC) print 'monitoring of %s started' % self.path added_flag = False # read and process events while True: try: if not added_flag: # on first iteration, add a watch on path: # watch path for events handled by mask. wm.add_watch(self.path, mask) added_flag = True notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: # ...until c^c signal print 'stop monitoring...' # stop monitoring notifier.stop() break except Exception, err: # otherwise keep on watching print err
def main(argv): if len(argv) == 1: print "Usage: %s [file]" % argv[0] return 1 path = argv[1] logging.basicConfig( level=logging.DEBUG, format="%(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s", datefmt="%H:%M:%S", filename=None # filename = "/tmp/filemon.log" ) logging.debug("Init Watcher (%s)" % path) class PClose(ProcessEvent): def process_default(self, event): logging.info("%s: %s: %s" % (getusers(event.pathname), event.pathname, str(event.maskname))) wm = WatchManager() notifier = Notifier(wm, PClose()) wm.add_watch(path, EventsCodes.ALL_FLAGS["ALL_EVENTS"], rec=True) logging.info("Waiting for updates") while True: notifier.process_events() if notifier.check_events(): notifier.read_events() return 0
def FSMonitor(path): wm = WatchManager() mask = IN_DELETE | IN_CREATE | IN_MODIFY notifier = Notifier(wm, EventHandler()) wm.add_watch(path, mask, auto_add=True, rec=True) print('now starting monitor % s' % (path)) while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break
class AutoLibraryUpdate(EventPlugin): PLUGIN_ID = "Automatic library update" PLUGIN_NAME = _("Automatic Library Update") PLUGIN_DESC = _("Keeps your library up to date with inotify. " "Requires %s.") % "pyinotify" # TODO: make a config option USE_THREADS = True event_handler = None running = False def enabled(self): if not self.running: wm = WatchManager() self.event_handler = LibraryEvent(app.library) # Choose event types to watch for # FIXME: watch for IN_CREATE or for some reason folder copies # are missed, --nickb FLAGS = ['IN_DELETE', 'IN_CLOSE_WRITE',# 'IN_MODIFY', 'IN_MOVED_FROM', 'IN_MOVED_TO', 'IN_CREATE'] mask = reduce(lambda x, s: x | EventsCodes.ALL_FLAGS[s], FLAGS, 0) if self.USE_THREADS: print_d("Using threaded notifier") self.notifier = ThreadedNotifier(wm, self.event_handler) # Daemonize to ensure thread dies on exit self.notifier.daemon = True self.notifier.start() else: self.notifier = Notifier(wm, self.event_handler, timeout=100) GLib.timeout_add(1000, self.unthreaded_callback) for path in get_scan_dirs(): print_d('Watching directory %s for %s' % (path, FLAGS)) # See https://github.com/seb-m/pyinotify/wiki/ # Frequently-Asked-Questions wm.add_watch(path, mask, rec=True, auto_add=True) self.running = True def unthreaded_callback(self): """Processes as much of the inotify events as allowed""" assert self.notifier._timeout is not None, \ 'Notifier must be constructed with a [short] timeout' self.notifier.process_events() # loop in case more events appear while we are processing while self.notifier.check_events(): self.notifier.read_events() self.notifier.process_events() return True # disable hook, stop the notifier: def disabled(self): if self.running: self.running = False if self.notifier: print_d("Stopping inotify watch...") self.notifier.stop()
class QNotifier(QThread): def __init__(self, wm, processor): self.event_queue = list() self._processor = processor self.notifier = Notifier(wm, NinjaProcessEvent(self.event_queue.append)) self.notifier.coalesce_events(True) self.keep_running = True QThread.__init__(self) def run(self): while self.keep_running: try: self.notifier.process_events() except OSError: pass # OSError: [Errno 2] No such file or directory happens e_dict = {} while len(self.event_queue): e_type, e_path = self.event_queue.pop(0) e_dict.setdefault(e_path, []).append(e_type) keys = e_dict.keys() while len(keys): key = keys.pop(0) event = e_dict.pop(key) if (ADDED in event) and (DELETED in event): event = [e for e in event if e not in (ADDED, DELETED)] for each_event in event: self._processor(each_event, key) if self.notifier.check_events(): self.notifier.read_events() self.notifier.stop()
def run(self): """Create the inotify WatchManager and generate FileSysEvents""" # Only capture events that git cares about self._wmgr = WatchManager() if self._is_pyinotify_08x(): notifier = Notifier(self._wmgr, FileSysEvent(self), timeout=self._timeout) else: notifier = Notifier(self._wmgr, FileSysEvent(self)) dirs_seen = set() added_flag = False # self._abort signals app termination. The timeout is a tradeoff # between fast notification response and waiting too long to exit. while not self._abort: if not added_flag: self._watch_directory(self._path) # Register files/directories known to git for filename in self._git.ls_files().splitlines(): directory = os.path.dirname(filename) self._watch_directory(directory) added_flag = True notifier.process_events() if self._is_pyinotify_08x(): check = notifier.check_events() else: check = notifier.check_events(timeout=self._timeout) if check: notifier.read_events() notifier.stop()
def run(self): """Create the inotify WatchManager and generate FileSysEvents""" if utils.is_win32(): self.run_win32() return # Only capture events that git cares about self._wmgr = WatchManager() if self._is_pyinotify_08x(): notifier = Notifier(self._wmgr, FileSysEvent(), timeout=self._timeout) else: notifier = Notifier(self._wmgr, FileSysEvent()) self._watch_directory(self._path) # Register files/directories known to git for filename in core.decode(self._git.ls_files()).splitlines(): filename = os.path.realpath(filename) directory = os.path.dirname(filename) self._watch_directory(directory) # self._running signals app termination. The timeout is a tradeoff # between fast notification response and waiting too long to exit. while self._running: if self._is_pyinotify_08x(): check = notifier.check_events() else: check = notifier.check_events(timeout=self._timeout) if not self._running: break if check: notifier.read_events() notifier.process_events() notifier.stop()
def startSentry(sentry_paths): """ Sentry Runner """ notifier = Notifier(wm, do_event()) for path in sentry_paths: wdd = wm.add_watch(sentry_paths[path].path, mask, rec=True) print 'watching %s ' % sentry_paths[path].path #wdd = wm.add_watch('/home/cmdln/sandbox/permissionminder/test', mask, rec=True) while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break except ConfigChange: notifier.stop() raise ConfigChange('Config Changed') break except: #from pdb import set_trace;set_trace() pass
def __init__( self, path, MountDetectedCallback, UnmountDetectedCallback ): wm = WatchManager() notifier = Notifier( wm, MountEvents( MountDetectedCallback, UnmountDetectedCallback ) ) wm.add_watch(path, pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_ISDIR ) while( True ): notifier.process_events() if notifier.check_events(): notifier.read_events() time.sleep( 0.1 )
def fs_monitor(path=need_remove_disk_file): wm = WatchManager() mask = FLAG['OP_FLAGS']['IN_CLOSE_WRITE'] | FLAG['OP_FLAGS']['IN_CLOSE_NOWRITE'] notifier = Notifier(wm, EventHandler()) wm.add_watch(path, mask, rec=True) # print('now starting monitor %s' % path) while True: notifier.process_events() if notifier.check_events(): notifier.read_events()
def Monitor(path): notifier = Notifier(wm, PTmp()) wdd = wm.add_watch(path, mask, rec=True) while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break
def Monitor(path): notifier = Notifier(wm, PTmp()) wdd = wm.add_watch(path, mask, rec=True) newDevice.put('/dev/waggle_coresense') while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break
def newDev(path): notifier = Notifier(wm, PTmpCreate()) wdd = wm.add_watch(path, maskCreate, rec=True) while True: # loop forever time.sleep(0.1) try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break
def main(args): """ args : [-h] [-r REGEX | -p REGEX] directory script example : react.py /local/data -p '*.hdf' 'echo $f' positional arguments : - directory: the directory which is recursively monitored - script: the script that is executed upon reaction optional arguments : -h, --help show this help message and exit -r REGEX, --regex REGEX files only trigger the reaction if their name matches this regular expression -p REGEX, --pattern REGEX files only trigger the reaction if their name matches this shell pattern """ parser = argparse.ArgumentParser(description='Launch a script if specified files change.') parser.add_argument('directory', help='the directory which is recursively monitored') group = parser.add_mutually_exclusive_group() group.add_argument('-r', '--regex', required=False, default=".*", help='files only trigger the reaction if their name matches this regular expression') group.add_argument('-p', '--pattern', required=False, dest="regex", action=PatternAction, help='files only trigger the reaction if their name matches this shell pattern') parser.add_argument("script", help="the script that is executed upon reaction") options = Options() args = parser.parse_args(namespace=options) #print sys.argv while True: wm = WatchManager() process = Process(options) notifier = Notifier(wm, process) mask = IN_DELETE | IN_CREATE | IN_CLOSE_WRITE wdd = wm.add_watch(options.directory, mask, rec=True) try: while True: notifier.process_events() if notifier.check_events(): notifier.read_events() except Reload: pass except KeyboardInterrupt: notifier.stop() break
def inotify_watch(): wm = WatchManager() mask = EventsCodes.ALL_FLAGS['IN_CLOSE_WRITE'] wdd = wm.add_watch('src', mask, rec=True) notifier = Notifier(wm, PTmp()) while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break
def Monitor(path, which_dev): notifier = Notifier(wm, PTmp()) wdd = wm.add_watch(path, mask, rec=True) # newDevice.put('/dev/ttyACM'+which_dev) newDevice.put(which_dev) while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break
def start_watcher(source, new_files, destination, bitrate): wm = WatchManager() process = Process(new_files, destination, bitrate) notifier = Notifier(wm, process) # TODO detect files moving from a dir to another wm.add_watch(source, IN_CLOSE_WRITE, rec=True) try: while True: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop()
def run(self): wm = WatchManager() mask = IN_DELETE | IN_CREATE | IN_MODIFY | IN_ATTRIB notifier = Notifier(wm, MyEventHandler()) wm.add_watch(self.path, mask, auto_add=True, rec=True) print("Now starting monitor {0}".format(self.path)) while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break
def socket_loop(self): wm = WatchManager() mask = pyinotify.IN_CREATE | pyinotify.IN_DELETE notifier = Notifier(wm, EventHandler(self)) wm.add_watch(VLC_CACHE_PATH, mask, rec=True) while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break
def Monitor(path): wm = WatchManager() mask = IN_DELETE | IN_CREATE | IN_MOVED_TO | IN_ATTRIB | IN_ACCESS | IN_CLOSE_WRITE notifier = Notifier(wm, EventHandler()) wm.add_watch(path, mask, rec=True) print '[+] Now Starting Monitor: %s' % (path) while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break
def FSMonitor(path='/var/log'): wm = WatchManager() mask = IN_DELETE | IN_CREATE |IN_MODIFY notifier = Notifier(wm, EventHandler()) wm.add_watch(path, mask,rec=True) print 'now starting monitor %s'%(path) while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break
def FSMonitor(path="."): wm = WatchManager() mask = IN_DELETE | IN_CREATE | IN_MODIFY | IN_ACCESS | IN_ATTRIB notifier = Notifier(wm, EventHandler()) wm.add_watch(path, mask, rec=True) print ("now starting monitor %s" % (path)) while True: try: notifier.process_events() # 绑定处理event方法 if notifier.check_events(): # 检查是否有有可读取的新event notifier.read_events() # 读取event,交给EventHandler处理 except KeyboardInterrupt: notifier.stop() break
def FSMonitor(path='.'): wm = WatchManager() mask = IN_DELETE | IN_CREATE | IN_MODIFY | IN_ATTRIB | IN_CLOSE_WRITE | IN_MOVED_FROM | IN_MOVED_TO | IN_DELETE_SELF | IN_MOVE_SELF notifier = Notifier(wm, EventHandler()) wm.add_watch(path, mask,auto_add=True,rec=True) print 'now starting monitor %s'%(path) while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break
def run(self): for i in self.path: self.init_watch(i) print '开始监控 %s' % (i) notifier = Notifier(self.wm, EventHandler()) while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break
def run(self): for i in self.path: self.init_watch(i) print('开始监控 %s' % (i)) notifier = Notifier(self.wm, EventHandler()) while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break
class InoTailer(BaseTailer): def __init__(self, file, should_read=True, callback=None, timeout=None): super(InoTailer, self).__init__(file, callback, timeout) if self.timeout: self.timeout *= 1000 self._should_read_myself = should_read if not hasattr(self.file, 'fileno') and self._should_read_myself: if not os.path.exists(self.file): raise DoesNotExist("Can't find %s. It does not seem to exist" % self.file) self.file = open(self.file) class Watcher(ProcessEvent): pass if callable(self.callback): setattr(Watcher, 'process_IN_MODIFY', self.callback) mask = IN_MODIFY self.wm = WatchManager() self.notifier = Notifier(self.wm, Watcher()) self.wm.add_watch(self.file.name, mask,) self._initial_lines = None if not self.at_end(): if self._should_read_myself: self._initial_lines = self.file.read().rstrip('\n').split('\n') else: self._initial_lines = True def at_end(self): return self.file.tell() == os.path.getsize(self.file.name) def check_once(self): if self._initial_lines: self._initial_lines, result = None, self._initial_lines return result self.notifier.process_events() if self.notifier.check_events(self.timeout): self.notifier.read_events() if self._should_read_myself: result = self.file.read().rstrip('\n').split('\n') return result return True return None def wait(self, with_timeout=False): timeout = None if with_timeout: timeout = self.timeout self.notifier.check_events(timeout)
class INotifyDriver(Component): channel = "inotify" def __init__(self, freq=1, timeout=1, channel=channel): super(INotifyDriver, self).__init__(channel=channel) self._freq = freq self._wm = WatchManager() self._notifier = Notifier(self._wm, self._process, timeout=timeout) def _sleep(self, rtime): # Only consider sleeping if _freq is > 0 if self._freq > 0: ctime = time.time() s = self._freq - (ctime - rtime) if s > 0: time.sleep(s) def __tick__(self): self._notifier.process_events() rtime = time.time() if self._notifier.check_events(): self._sleep(rtime) self._notifier.read_events() def _process(self, event): dir = event.dir mask = event.mask path = event.path name = event.name pathname = event.pathname #print dir, mask, path, name, pathname for k, v in EVENT_MAP.iteritems(): if mask & k: e = v(name, path, pathname, dir) c = e.name.lower() self.push(e, c) def add(self, path, mask=None, recursive=True): mask = mask or MASK self._wm.add_watch(path, mask, rec=recursive) def remove(self, path, recursive=False): wd = self._wm.get_wd(path) if wd: self._wm.rm_watch(wd, rec=recursive)
def run(self): sys.stdout.write('Daemon started with pid %d\n' % os.getpid()) wm = WatchManager() mask = IN_CREATE | IN_MODIFY notifier = Notifier(wm, EventHandler()) wdd = wm.add_watch(FSpath, mask, rec=True) print 'now starting monitor %s' % (FSpath) while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break
def Monitor(path='.'): wm=WatchManager() mask=IN_CREATE|IN_DELETE handler=Handler() notifier=Notifier(wm,handler) wm.add_watch(path,mask,rec=True) print 'now start monitor ... %s ' %path while True: try: notifier.process_events() if notifier.process_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break
def run (self): global watchQueue toWatch = watchQueue.get() if toWatch : notifier = Notifier(wm, PTmpCreate()) wdd = wm.add_watch(toWatch, maskCreate, rec=True) while True: # loop forever time.sleep(1) try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break
def FsMonitor(path='.'): wm = WatchManager() mask = IN_DELETE | IN_CREATE | IN_MODIFY notifier = Notifier(wm, EventHandler()) wm.add_watch(path, mask, auto_add=True, rec=True) print("Now Start Monitoring %s.\n" % path) while True: try: notifier.process_events() notifier.read_events() except KeyboardInterrupt: print("Keyboard Interrupt.") notifier.stop() break
def __monitor(self): wm = WatchManager() mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE | pyinotify.IN_MODIFY | pyinotify.IN_ACCESS | pyinotify.IN_ATTRIB notifier = Notifier(wm,self.eventHandler) wm.add_watch(self.path,mask,rec=True) print('now starting monitor %s',self.path) while True: try: notifier.process_events() # 绑定处理event方法 if notifier.check_events(): # 检查是否有有可读取的新event notifier.read_events() # 读取event,交给EventHandler处理 except KeyboardInterrupt: notifier.stop() break
def run(self): self.send_from_outbox() wm = WatchManager() wm.add_watch(self.outbox_path.__str__(), IN_CREATE) notifier = Notifier(wm, MailerEventHandler(self.send_from_outbox)) while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break
def fsMonitor(path="/opt/deviceMonitor/access.log"): wm = WatchManager() mask = IN_DELETE | IN_CREATE | IN_MODIFY notifier = Notifier(wm, eventHandler()) wm.add_watch(path, mask, auto_add=True, rec=True) #print "now starting monitor %s." %path while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break
def FSMonitor(path='../public/print'): wm = WatchManager() mask = IN_CLOSE_WRITE | IN_CREATE #IN_DELETE | IN_CREATE | IN_MODIFY notifier = Notifier(wm, EventHandler()) wm.add_watch(path, mask, rec=True) print "now starting monitor %s" % (path) while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() print KeyboardInterrupt break
def run(self): mask = IN_DELETE | IN_CREATE | IN_MODIFY wm = WatchManager() notifier = Notifier(wm, MyEventHandler()) wm.add_watch(scriptdir+"/Common", mask, auto_add= True, rec=True) wm.add_watch(scriptdir+"/Special", mask, auto_add= True, rec=True) wm.add_watch(scriptdir+"/Override", mask, auto_add= True, rec=True) while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop()
def run(self): logger.info( '['+self.name+'] watching: '+ self.spath ) wm = WatchManager() mask = EventsCodes.OP_FLAGS["IN_DELETE"] | EventsCodes.OP_FLAGS["IN_CREATE"] |EventsCodes.OP_FLAGS["IN_MODIFY"] | EventsCodes.OP_FLAGS["IN_MOVED_TO"] | EventsCodes.OP_FLAGS["IN_MOVED_FROM"] notifier = Notifier(wm, WorkEvent("WEVNT",self.workqueue)) wm.add_watch(self.spath, mask,rec=True) while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break
def fsMonitor(path="."): wm = WatchManager() # 创建监控组 mask = IN_CREATE | IN_DELETE | IN_MODIFY wm.add_watch(path, mask, auto_add=True, rec=True) # 将具体路径的监控加入监视组 notifier = Notifier(wm, EventHandler()) # 创建事件处理器,参数为监视组和对应的事件处理函数 print("now starting monitor %s." % path) while True: try: notifier.process_events() # 对事件队列中的事件逐个调用事件处理函数 if notifier.check_events(): # 等待 检查是否有新事件到来 print("check event true") notifier.read_events() # 将新事件读入事件队列 except KeyboardInterrupt: print("keyboard interrupt") notifier.stop() break
def FSMonitor(): back_sql() wm = WatchManager() mask = IN_CREATE | IN_MODIFY notifier = Notifier(wm, PFilePath()) wdd = wm.add_watch(find_path, mask, rec=True) print("now starting monitor %s" % find_path) while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break
def Monitor(path_list): wm = WatchManager() notifier = Notifier(wm, MyProcessEvent()) for path in path_list: print '增加监控路径: %s' % path wm.add_watch(os.path.abspath(path), MASK, rec=True, auto_add=True) try: while 1: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() return
def run(self): notifier = Notifier(self.watchmanager, self.event) descriptor = self.watchmanager.add_watch( self.folder, EventsCodes.ALL_FLAGS['ALL_EVENTS'], rec=self.recursive) logging.info('Watching %i folders', len(descriptor)) if self.first_run: self.event.run_cmd(True) while True: try: notifier.process_events() if notifier.check_events(): notifier.read_events() except KeyboardInterrupt: notifier.stop() break
class INotifyDriver(Component): channel = "inotify" def __init__(self, freq=1, timeout=1, channel=channel): super(INotifyDriver, self).__init__(channel=channel) self._freq = freq self._wm = WatchManager() self._notifier = Notifier(self._wm, self._process, timeout=timeout) def _sleep(self, rtime): # Only consider sleeping if _freq is > 0 if self._freq > 0: ctime = time.time() s = self._freq - (ctime - rtime) if s > 0: time.sleep(s) def __tick__(self): self._notifier.process_events() rtime = time.time() if self._notifier.check_events(): self._sleep(rtime) self._notifier.read_events() def _process(self, event): dir = event.dir mask = event.mask path = event.path name = event.name pathname = event.pathname for k, v in EVENT_MAP.iteritems(): if mask & k: e = v(name, path, pathname, dir) c = e.name.lower() self.push(e, c) def add(self, path, mask=None, recursive=False): mask = mask or MASK self._wm.add_watch(path, mask, rec=recursive) def remove(self, path, recursive=False): wd = self._wm.get_wd(path) if wd: self._wm.rm_watch(wd, rec=recursive)
class MyNotify(object): def __init__(self, path): self.wm = WatchManager() mask = IN_DELETE | IN_CLOSE_WRITE self.notifier = Notifier(self.wm, MyProcessEvent()) self.wm.add_watch(path, mask, rec=True) def run(self): signal.signal(signal.SIGHUP, lambda: sys.exit(0)) while True: try: self.notifier.process_events() if self.notifier.check_events(): self.notifier.read_events() except Exception: self.notifier.stop() break
def FsMonitor(path='.'): wm = WatchManager() mask = IN_DELETE | IN_CREATE | IN_MODIFY notifier = Notifier(wm, EventHandler()) wm.add_watch(path, mask, auto_add=True, rec=True) print "[*] now starting monitor %s." % path while True: try: notifier.process_events() if notifier.check_events(): print "check event true." notifier.read_events() except KeyboardInterrupt: print "keyboard Interrupt." notifier.stop() break