def watch_config_changes(config_path, queues, nuimo_apps, processes, ble_adapter_name): class ModificationHandler(pyinotify.ProcessEvent): def process_IN_CLOSE_WRITE(self, event): if hasattr(event, 'pathname') and event.pathname == config_path: logger.info("Config file was changed, reloading it...") update_from_config_file(config_path, queues, nuimo_apps, processes, ble_adapter_name) handler = ModificationHandler() watch_manager = pyinotify.WatchManager() notifier = pyinotify.Notifier(watch_manager, handler) # IN_CLOSE_WRITE is fired when the file was closed after modification # in opposite to IN_MODIFY which is called for each partial write watch_manager.add_watch(config_path, pyinotify.IN_CLOSE_WRITE) logger.info("Listening to changes of: %s", config_path) notifier.loop() logger.info("Stopped listening to changes of: %s", config_path)
def _loop_linux(self, loop_callback): """loop implementation for linux platform""" import pyinotify handler = self._handle class EventHandler(pyinotify.ProcessEvent): def process_default(self, event): handler(event) watch_manager = pyinotify.WatchManager() event_handler = EventHandler() notifier = pyinotify.Notifier(watch_manager, event_handler) mask = pyinotify.IN_CLOSE_WRITE for watch_this in self.watch_dirs: watch_manager.add_watch(watch_this, mask) notifier.loop(loop_callback)
def __init__(self, file_name: str, output: Callable[[str], NoReturn] = sys.stdout.write, interval: int = 1, len_line: int = 1024): self.file_name: str = file_name self.output: Callable[[str], NoReturn] = output self.interval: int = interval self.len_line: int = len_line wm = pyinotify.WatchManager() # 创建WatchManager对象 inotify_event_handler = InotifyEventHandler(**dict( filename=file_name, wm=wm, output=output)) # 实例化我们定制化后的事件处理类, 采用**dict wm.add_watch('/tmp', multi_event) # 添加监控的目录,及事件 self.notifier = pyinotify.Notifier( wm, inotify_event_handler) # 在notifier实例化时传入,notifier会自动执行 self.inotify_event_handle: 'InotifyEventHandler' = inotify_event_handler
def build_notifier(**kwargs): wm = pyinotify.WatchManager() mask = kwargs.get('mask', 0) events = kwargs.get('events') if events: if type(events) not in [list, tuple, set]: events = [events] mask |= build_mask(*events) path = kwargs.get('path') callback = kwargs.get('callback') run_loop = kwargs.get('run_loop', True) handler = EventHandler(callback=callback) notifier = pyinotify.Notifier(wm, handler) wm.add_watch(path, mask) if run_loop: notifier.loop() else: return {'handler': handler, 'notifier': notifier}
def main(): activity_db = ActivityDB() activity_db.create() watch_manager = pyinotify.WatchManager() watch_manager.add_watch('/dev/input', mask=pyinotify.ALL_EVENTS) notifier = pyinotify.Notifier( watch_manager, None, timeout=ActivityDB.timeout ) while True: while notifier.check_events(): notifier.read_events() now = datetime.datetime.now() activity_db.save_timestamp(now) break time.sleep(ActivityDB.timeout)
def run(self): signal.signal(signal.SIGINT, self.terminate) signal.signal(signal.SIGTERM, self.terminate) wm = pyinotify.WatchManager() handler = EventHandler(watcher=self, extensions=self.extensions) notifier = pyinotify.Notifier(wm, handler) wm.add_watch(self.watchdir, handler.events, rec=False) try: LOG.debug("FileWatcher: %s: notifier waiting ..." % self.name) notifier.loop() finally: LOG.debug("FileWatcher: %s: notifier returned" % self.name) self.terminate(None, None) LOG.debug("FileWatcher: %s: processor returned" % self.name) self.processor.join() return True
def thread_notify(s): print("Creating notify") # Instanciate a new WatchManager (will be used to store watches). wm = pyinotify.WatchManager() flags = pyinotify.IN_CREATE | pyinotify.IN_MOVED_TO | pyinotify.IN_MOVED_FROM | pyinotify.IN_DELETE | pyinotify.IN_CLOSE_WRITE handler = EventHandler(s) # Associate this WatchManager with a Notifier (will be used to report and # process events). notifier = pyinotify.Notifier(wm, handler) # Add a new watch on 'drive' for the required events wdd = wm.add_watch(PATH, flags, rec=False) # Loop forever and handle events. notifier.loop()
def setup_notifier(self): '''Set up and configure the inotify machinery and logic. This takes the provided or default path_template and builds a list of directories we need to watch for database updates. It then validates and passes these on to the various pyinotify pieces as necessary and finally builds and returns a notifier object.''' transaction.commit_manually() arches = Arch.objects.filter(agnostic=False) repos = Repo.objects.all() transaction.set_dirty() arch_path_map = {arch: None for arch in arches} all_paths = set() total_paths = 0 for arch in arches: combos = ({ 'repo': repo.name.lower(), 'arch': arch.name } for repo in repos) # take a python format string and generate all unique combinations # of directories from it; using set() ensures we filter it down paths = {self.path_template % values for values in combos} total_paths += len(paths) all_paths |= paths arch_path_map[arch] = paths logger.info('Watching %d total paths', total_paths) logger.debug(all_paths) # sanity check- basically ensure every path we created from the # template mapped to only one architecture if total_paths != len(all_paths): raise CommandError('path template did not uniquely ' 'determine architecture for each file') # A proper atomic replacement of the database as done by rsync is type # IN_MOVED_TO. repo-add/remove will finish with a IN_CLOSE_WRITE. mask = pyinotify.IN_CLOSE_WRITE | pyinotify.IN_MOVED_TO manager = pyinotify.WatchManager() for name in all_paths: manager.add_watch(name, mask) handler = EventHandler(arch_paths=arch_path_map) return pyinotify.Notifier(manager, handler)
def run(self): if self.infile: print('Using infile') self.notifiers = [] self.associations = {} self.files = {} infiles = self.escape(self.infile) for filechan in infiles.split(';'): temparr = filechan.split(':') filename = self.unescape(temparr[0]) try: print('Opening: ' + filename) f = open(filename) f.seek(0, 2) self.files[filename] = f except IOError: print('Failed to open file: ' + filename) self.files[filename] = None pass wm = pyinotify.WatchManager() mask = pyinotify.IN_MODIFY | pyinotify.IN_CREATE wm.watch_transient_file(filename, mask, EventHandler) notifier = EchoNotifier(pyinotify.Notifier(wm)) self.notifiers.append(notifier) # Does this file have channel associations? if len(temparr) > 1: chans = self.unescape(temparr[1]) self.associations[filename] = chans for notifier in self.notifiers: print('Starting notifier loop') notifier.start() else: while True: try: s = raw_input() # this throws an exception if not connected. s = beautify_message(s) self.bot.connection.privmsg(self.chans, s.replace('\n', '')) except EOFError: # Once the input is finished, the bot should exit break except Exception: pass
def main(): if debug: print("Foreground test mode enabled, no POST requests will be sent") # Start the git thread git_thread = PubSubClient() git_thread.url = config.get('PubSub', 'git') git_thread.start() # Start the svn thread svn_thread = PubSubClient() svn_thread.url = config.get('PubSub', 'svn') svn_thread.start() # Idle and check for updates to the config if haveinotify: handler = ModHandler() wm = pyinotify.WatchManager() notifier = pyinotify.Notifier(wm, handler) wdd = wm.add_watch(path + '/svngit2jira.cfg', pyinotify.IN_CLOSE_WRITE) notifier.loop() else: modded = os.stat(path + '/svngit2jira.cfg').st_mtime while True: time.sleep(5) xmodded = os.stat(path + '/svngit2jira.cfg').st_mtime if xmodded != modded: modded = xmodded logging.info("Configuration was updated, reloading") # Remove all tracking sections (we'll reload them in a bit) for section in config.sections(): if re.match("Tracking:(.+)", section): config.remove_section(section) # Re-read config config.read(path + '/svngit2jira.cfg') projects = [] for section in config.sections(): match = re.match("Tracking:(.+)", section) if match: projects.append(match.group(1)) projects.sort() logging.info("Found the following trackers: %s", ', '.join(projects))
def main(args={}): """ main function :param args - dict of arguments """ # watch manager wm = pyinotify.WatchManager() wm.add_watch(args.config_path, pyinotify.IN_CREATE, rec=True) # event handler eh = ConfigmapHandler(args.pgbouncer_host, args.pgbouncer_port, args.pgbouncer_user, args.pgbouncer_password, args.pgbouncer_database, args.pgbouncer_reload_timeout) # notifier log.info("Entering event loop...") notifier = pyinotify.Notifier(wm, eh) notifier.loop()
def __init__(self, watch_files=None): if watch_files is None: self.watch_files = frozenset([ LIBVIRT_DNSMASQ_LEASE_FILE, LIBVIRT_DNSMASQ_STATUS_FILE, ]) else: self.watch_files = watch_files self.wm = pyinotify.WatchManager() self.process_event = ProcessEvent() # API-by-inheritence: must avoid namespace collision, and told # by upstream not to override __init__, so cannot provide parameters. # So we initialise here. What a hack. This is why I consider # API-by-inheritence in dynamic languages (where subclasses share the # same attribute namespace) harmful. self.process_event._uvtool_watch_files = self.watch_files self.process_event._uvtool_modified = False self.notifier = pyinotify.Notifier(self.wm, self.process_event)
def test_record_length(token): logging.info("In Record Test") multitask = utils.Multitask() src_path = conf.RECORD_SRC_DIR wm = pyinotify.WatchManager() wm.add_watch(src_path, pyinotify.IN_CLOSE_WRITE, utils.inCloseWrite) notifier = pyinotify.Notifier(wm) publisher = utils.Ffmpeg() publisher.input(conf.VIDEOS["countdown"]) publisher.output( utils.get_rtmp_path(conf.RTMP_HLS, conf.RESOURCE_ID["test-resource-1"], token), '-f', 'flv') multitask.add(notifier.loop) multitask.add(publisher.push, conf.PUSH_VALID) logging.info("Initialising notifier and video stream") multitask.run()
def __init__(self, path): self.log = logging.getLogger('Directory') self.path = path self.scheduled = False self.rescan() self.log.debug('setting up inotify watch for %s', self.path) wm = pyinotify.WatchManager() notifier = pyinotify.Notifier(wm, timeout=10, default_proc_fun=self.inotify_callback) wm.add_watch( self.path, #pyinotify.ALL_EVENTS, pyinotify.IN_DELETE | pyinotify.IN_CREATE | pyinotify.IN_MODIFY, rec=True) GLib.io_add_watch(notifier._fd, GLib.IO_IN, self.io_callback, notifier)
def __init__(self, queue_path, result_path): self.queue_path = queue_path self.result_path = result_path self.fd = open(queue_path, 'r+') self.wm = pyinotify.WatchManager() handler = self.check_queue class EventHandler(pyinotify.ProcessEvent): def process_default(self, event): handler() self.handler = EventHandler() self.notifier = pyinotify.Notifier(self.wm, self.handler) self.wdd = self.wm.add_watch(self.queue_path, pyinotify.IN_DELETE, rec=True) self.start_monitor()
def main(): global notifier, lastsize, wm, wd, monfile monfile = os.path.abspath('./a') print("path={0}".format(monfile)) lastsize = os.stat(monfile).st_size wm = pyinotify.WatchManager() notifier = pyinotify.Notifier(wm, EventHandler()) wd = wm.add_watch(monfile, pyinotify.IN_MODIFY) wm.add_watch( os.path.dirname(monfile), pyinotify.IN_DELETE | pyinotify.IN_CREATE | pyinotify.IN_MOVED_FROM | pyinotify.IN_MOVED_TO) print("watching {0} ...".format(monfile)) while True: notifier.process_events() if notifier.check_events(): notifier.read_events()
def main(options): def simply_process_rawfile(file_path): """ Wraps `process_rawfile` to take a single argument (file_path). This is the trivial, single threaded version - occasionally useful for debugging purposes. """ newfile_callback(file_path) summary = process_rawfile(file_path) processed_callback(summary) def asynchronously_process_rawfile(file_path): """ Wraps `process_rawfile` to take a single argument (file_path). This version runs 'process_rawfile' asynchronously via the pool. This provides parallel processing, at the cost of being harder to debug if anything goes wrong (see notes on exception catching above) """ pool.apply_async(process_rawfile, [file_path], callback=processed_callback) """Define processing logic and fire up the watcher""" watch_dir = options.watch_dir try: pool = multiprocessing.Pool(options.nthreads) handler = RsyncNewFileHandler( nthreads=options.nthreads, file_predicate=is_rawfile, #file_processor=simply_process_rawfile file_processor=asynchronously_process_rawfile) wm = pyinotify.WatchManager() notifier = pyinotify.Notifier(wm, handler) wm.add_watch(options.watch_dir, handler.mask, rec=True) log_preamble(options) notifier.loop() finally: pool.close() pool.join() return 0
def main(): optlist, arguments = getopt.getopt(sys.argv[1:], '', ["dir="]) ldir = "" for k, v in optlist: if k == '--dir': ldir = v break if not os.path.exists(ldir): print("can't pyinotify dir: '%s'. it don't exist" % ldir) sys.exit(0) wm = pyinotify.WatchManager() notifier = pyinotify.Notifier(wm) print("Watching: '%s'" % ldir) wm.add_watch(ldir, pyinotify.ALL_EVENTS, auto_add=True, rec=True, proc_fun=AT()) notifier.loop()
def watch(self, id, path): """ Sets recursive watching on specified directory """ if self.notifier is None: self.wm = pyinotify.WatchManager() self.notifier = pyinotify.Notifier( self.wm, timeout=10, default_proc_fun=self._process) self.glibsrc = GLib.idle_add(self._process_events) added = self.wm.add_watch( path.encode("utf-8"), pyinotify.IN_CLOSE_WRITE | pyinotify.IN_MOVED_TO | pyinotify.IN_MOVED_FROM | pyinotify.IN_DELETE | pyinotify.IN_CREATE, rec=True, quiet=False) if path in added: # Should be always self.wds[path] = added[path] log.verbose("Watching %s", path)
def main(): parser = argparse.ArgumentParser(description='Generate documentation.') parser.add_argument('--watch', action='store_true', help="Use pyinotify to watch for changes") args = parser.parse_args() if args.watch: import pyinotify import functools wm = pyinotify.WatchManager() notifier = pyinotify.Notifier(wm) wm.add_watch('CONFIGURATION.yaml', pyinotify.IN_CLOSE_WRITE) wm.add_watch('template.html', pyinotify.IN_CLOSE_WRITE) on_loop_func = functools.partial(render) notifier.loop(daemonize=False, callback=on_loop_func) else: render(None)
def inotify_code_changed(): files = set() for filename in filter( lambda v: v, map(lambda m: getattr(m, "__file__", None), sys.modules.values())): if filename.endswith(".pyc") or filename.endswith(".pyo"): filename = filename[:-1] if not os.path.exists(filename): continue # File might be in an egg, so it can't be reloaded. files.add(filename) wm = pyinotify.WatchManager() notifier = pyinotify.Notifier(wm) min_update_interval = datetime.timedelta(seconds=1) def update_watch(sender=None, **kwargs): global _last_update if _last_update is not None and \ datetime.datetime.now() - _last_update < min_update_interval: return _last_update = datetime.datetime.now() mask = pyinotify.EventsCodes.IN_MODIFY \ | pyinotify.EventsCodes.IN_DELETE \ | pyinotify.EventsCodes.IN_ATTRIB \ | pyinotify.EventsCodes.IN_MOVED_FROM \ | pyinotify.EventsCodes.IN_MOVED_TO \ | pyinotify.EventsCodes.IN_CREATE for path in files: wm.add_watch(path, mask) signals.request_finished.connect(update_watch) update_watch() # Block forever notifier.check_events(timeout=None) notifier.stop() # If we are here the code must have changed. return True
def run_server(args): """ launches a preview server """ if not path.exists(args.origin): print "Error: Can't find origin directory." print "Aborting" sys.exit() cwd = getcwd() if not path.exists(path.join(args.origin, O)): print "Error: Can't find output directory." print "Aborting" sys.exit() handler = RequestHandler httpd = Server((HOST, args.port), handler) if args.noauto: print "[{}] Live at http://{}:{}".format( strftime("%H:%M:%S", localtime()), HOST, args.port) try: chdir(path.join(cwd, args.origin, O)) httpd.serve_forever() except KeyboardInterrupt: print "Aborting" sys.exit() else: t = threading.Thread(target=httpd.serve_forever) t.daemon = True t.start() print "[{}] Live at http://{}:{}".format( strftime("%H:%M:%S", localtime()), HOST, args.port) wm = pyinotify.WatchManager() handler = EventHandler(args) notifier = pyinotify.Notifier(wm, handler) mask = pyinotify.IN_CLOSE_WRITE | pyinotify.IN_MOVED_TO | pyinotify.IN_MOVED_FROM | pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_ATTRIB wm.add_watch([ path.join(cwd, args.origin, A), path.join(cwd, args.origin, C), path.join(cwd, args.origin, T) ], mask, auto_add=True, rec=True) chdir(path.join(cwd, args.origin, O)) notifier.loop()
def __init__( self, player_list, communication_files_directory='/usr/local/home/u180455/Desktop/Project/MLFYP_Project/MLFYP_Project/pokercasino/botfiles' ): self.communication_files_directory = communication_files_directory self.player_list = player_list # watch manager wm = pyinotify.WatchManager() wm.add_watch(self.communication_files_directory, pyinotify.ALL_EVENTS, rec=True) # event handler kwargs = {"player_list": self.player_list} eh = MyEventHandler(**kwargs) #**kwargs # notifier notifier = pyinotify.Notifier(wm, eh) notifier.loop()
def Run(): mask = pyinotify.IN_DELETE | pyinotify.IN_CLOSE_WRITE | pyinotify.IN_MOVED_TO wdd = wm.add_watch('/home/winddori/dev/TA_lite/data/msens', mask, rec=True) class EventHandler(pyinotify.ProcessEvent): def process_IN_CREATE(self, event): print "Creating:", event.pathname def process_IN_DELETE(self, event): print "Removing:", event.pathname def process_IN_CLOSE_WRITE(self, event): print "File was close write:", event.pathname handler = EventHandler() #notifier = pyinotify.Notifier(wm, handler, timeout=5) notifier = pyinotify.Notifier(wm, handler) notifier.loop()
def __init__(self, watchdir="/dev/shm", prefix="", postfix="", addcb=None, remcb=None, modcb=None): self.prefix = prefix self.postfix = postfix self.prelen = len(prefix) self.postlen = len(postfix) self.addcb = addcb self.remcb = remcb self.modcb = modcb self.mywm = pyinotify.WatchManager() flags = pyinotify.IN_DELETE | pyinotify.IN_CREATE #if modcb!=None: # flags|=pyinotify.IN_MODIFY self.mywm.add_watch(watchdir, flags) self.notifier = pyinotify.Notifier(self.mywm, self)
class FlagMonitor(object): mask = pyinotify.IN_ACCESS # flag has been read wm = pyinotify.WatchManager() def __init__(self,path='flag'): self.path = path class EventHandler(pyinotify.ProcessEvent): def process_IN_OPEN(self,event): with open(event.pathname) as f: print f.read() handler = EventHandler() notifier = pyinotify.Notifier(wm, handler) def add(self): wdd = self.wm.add_watch(self.path,pyinotify.ALL_EVENTS) def run(self): self.notifier.loop()
def main(): watch_class = WatchHandler() # 停止laravels print('停止laravels...') os.system("php " + watch_class.base_path + "/bin/laravels stop") # 启动laravels print('启动laravels...') os.system("php " + watch_class.base_path + "/bin/laravels start -d") wm = pyinotify.WatchManager() wm.add_watch(watch_class.watch_file_path, pyinotify.ALL_EVENTS, rec=True) print('开始监听...') notifier = pyinotify.Notifier(wm, watch_class) notifier.loop()
def watchLinux(path): # http://trac.dbzteam.org/pyinotify/wiki/Tutorial try: import pyinotify wm = pyinotify.WatchManager() mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE # Events to watch for class HandleEvents(pyinotify.ProcessEvent): def process_IN_CREATE(self, event): print 'ADDED: ', event.pathname logToDB('ADDED',event.pathname) def process_IN_DELETE(self, event): print 'REMOVED: ', event.pathname logToDB('REMOVED',event.pathname) notifier = pyinotify.Notifier(wm,HandleEvents()) wdd = wm.add_watch(path,mask,rec=True,auto_add=True) notifier.loop() except KeyboardInterrupt: wm.rm_watch(wdd.values()) notifier.stop() db.close() sys.exit()
def main(): if len(sys.argv) != 3: print "Usage: python watch_sync.py watched_local_dir remote_dir" sys.exit(1) wm = pyinotify.WatchManager() mask = pyinotify.IN_CREATE | pyinotify.IN_DELETE | \ pyinotify.IN_MODIFY | pyinotify.IN_CLOSE_WRITE | pyinotify.IN_MOVED_FROM | pyinotify.IN_MOVED_TO handler = EventHandler(sys.argv[1],sys.argv[2]) notifier = pyinotify.Notifier(wm, handler) excl_lst = ['^\..*'] excl = pyinotify.ExcludeFilter(excl_lst) wdd = wm.add_watch(sys.argv[1], mask, rec=True,exclude_filter=excl) try: notifier.loop() except pyinotify.NotifierError, err: print >> sys.stderr, err
def main(): args = sys.argv[1:] if len(args) > 0: watch_dir = args[0] else: print("Usage: {0} directory_to_watch".format(sys.argv[0])) exit(1) # watch manager wm = pyinotify.WatchManager() wm.add_watch(watch_dir, pyinotify.IN_CLOSE_WRITE | pyinotify.IN_MOVED_TO | pyinotify.IN_MOVED_FROM, rec=True) # event handler eh = MyEventHandler() # notifier notifier = pyinotify.Notifier(wm, eh) notifier.loop()