def addWatch(self, mask, folder, recursive, command, prefix=""): wm = pyinotify.WatchManager() handler = EventHandler(command, recursive, mask, self, prefix) self.wdds.append(wm.add_watch(folder, mask, rec=recursive)) # BUT we need a new ThreadNotifier so I can specify a different # EventHandler instance for each job # this means that each job has its own thread as well (I think) n = pyinotify.ThreadedNotifier(wm, handler) self.notifiers.append(pyinotify.ThreadedNotifier(wm, handler)) n.start()
def startMonitor(self): settings = Setting() self.ASSETSTORE_ID = settings.get(PluginSettings.ASSETSTORE_ID) self.assetstore = AssetstoreModel().load(self.ASSETSTORE_ID) self.MONITOR_PARTITION = settings.get(PluginSettings.MONITOR_PARTITION) self.DESTINATION_TYPE = settings.get(PluginSettings.DESTINATION_TYPE) self.DESTINATION_ID = settings.get(PluginSettings.DESTINATION_ID) self.destination = ModelImporter.model(self.DESTINATION_TYPE).load( self.DESTINATION_ID, user=self.getCurrentUser(), level=AccessType.WRITE, exc=True) wm = pyinotify.WatchManager() # Watch Manager mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE | pyinotify.IN_MODIFY self.notifier = pyinotify.ThreadedNotifier( wm, EventHandler(self.assetstore, self.destination, self.DESTINATION_TYPE, self.MONITOR_PARTITION)) wdd = wm.add_watch(self.MONITOR_PARTITION, mask, rec=True, auto_add=True) self.notifier.start() SettingDefault.defaults.update({PluginSettings.MONITOR: True}) return {PluginSettings.MONITOR: settings.get(PluginSettings.MONITOR)}
def watchfiles(origin, destination, quarentine, vt, eh): """ """ interval = 20 # 20 segs (4 every minute) for a public api wm = pyinotify.WatchManager() wm.add_watch(origin, pyinotify.ALL_EVENTS) event_notifier = pyinotify.ThreadedNotifier(wm, eh) event_notifier.start() sc = sched.scheduler(time.time, time.sleep) sc.enter(interval, 1, process_pending, ( sc, vt, eh, interval, destination, quarentine, )) try: sc.run() except (KeyboardInterrupt, SystemExit): print(MSG_EXITING) event_notifier.stop() sys.exit()
def __init__(self, filename): Gtk.ScrolledWindow.__init__(self) self.filename = filename self.changed = 0 self.update_id = 0 self.set_shadow_type(Gtk.ShadowType.ETCHED_IN) self.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) self.textview = Gtk.TextView() self.textview.set_editable(False) self.add(self.textview) self.textbuffer = self.textview.get_buffer() self.show_all() self.get_updates() handler = FileWatchHandler(view=self) watch_manager = pyinotify.WatchManager() self.notifier = pyinotify.ThreadedNotifier(watch_manager, handler) watch_manager.add_watch(filename, (pyinotify.IN_CLOSE_WRITE | pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_MODIFY)) self.notifier.start() self.connect("destroy", self.on_destroy) self.connect("size-allocate", self.on_size_changed)
def __init__(self): if InotifyManager._process_event is None: InotifyManager._process_event = RecordingProcessEvent() InotifyManager._watch_manager = pyinotify.WatchManager() InotifyManager._notifier = pyinotify.ThreadedNotifier( self._watch_manager, self._process_event) InotifyManager._notifier.start()
def start_a_monitor(**kwargs): _wm = pyinotify.WatchManager() if kwargs.__contains__('multiline') and kwargs.__contains__('tags'): negate = kwargs['multiline'].get('negate') or False _handler = TagAndMultilineEventHandler( queue=kwargs['queue'], fields=kwargs['fields'], multi_negate=negate, tag_head_pattern=kwargs['tags']['forward'], multi_head_pattern=kwargs['multiline']['patterns']) elif kwargs.__contains__('multiline'): negate = kwargs['multiline'].get('negate') or False _handler = MultilineEventHandler( queue=kwargs['queue'], fields=kwargs['fields'], multi_negate=negate, multi_head_pattern=kwargs['multiline']['patterns']) elif kwargs.__contains__('tags'): _handler = TagsEventHandler(queue=kwargs['queue'], fields=kwargs['fields'], tag_head_pattern=kwargs['tags'['forward']]) else: _handler = SimpleEventHandler(queue=kwargs['queue'], fields=kwargs['fields']) _notifier = pyinotify.ThreadedNotifier(_wm, _handler) _notifier.daemon = True _wm.add_watch(path=kwargs['paths'], mask=pyinotify.IN_MODIFY, rec=True, do_glob=True, quiet=True) return _notifier
def test_setup_watcher(self, tmpdir): incoming = str(tmpdir.mkdir('incoming')) config.config.set('pgwatcher', 'incoming', incoming) watcher = pgwatcher.setup_watcher() files = [] def callback(event): with open(event.pathname, 'r') as f: data = f.read() files.append(data) self.notifier = pyinotify.ThreadedNotifier(watcher, callback) self.notifier.start() with open(os.path.join(incoming, 'foo'), 'w') as f: f.write('foo') time.sleep(0.1) # paranoia, make sure file isn't read too early f.write('bar') with open(os.path.join(incoming, 'bar'), 'w') as f: f.write('bar') time.sleep(0.1) f.write('foo') while len(files) < 2: time.sleep(0.01) foo, bar = files assert foo == 'foobar' assert bar == 'barfoo' self.notifier.stop() self.notifier = None
def open(self): """Open module.""" Module.open(self) import pyinotify class EventHandler(pyinotify.ProcessEvent): """Event handler for file watcher.""" def __init__(self, main, *args, **kwargs): """Create event handler.""" pyinotify.ProcessEvent.__init__(self, *args, **kwargs) self.main = main def process_IN_CLOSE_WRITE(self, event): """React to IN_CLOSE_WRITE events.""" self.main.add_image(event.pathname) # start watching directory if self._watchpath: log.info('Start watching directory %s for changes...', self._watchpath) wm = pyinotify.WatchManager() wm.add_watch(self._watchpath, pyinotify.IN_CLOSE_WRITE) self._notifier = pyinotify.ThreadedNotifier( wm, default_proc_fun=EventHandler(self)) #, name='observer') self._notifier.start()
def _start_frontend(self, restart=False): """Check if it is enabled and start the frontend http & websocket""" self.log(self.config, self.config.frontendenabled, lvl=verbose) if self.config.frontendenabled and not self.frontend_running or restart: self.log("Restarting webfrontend services on", self.frontend_target) self.static = Static("/", docroot=self.frontend_target).register(self) self.websocket = WebSocketsDispatcher("/websocket").register(self) self.frontend_running = True if self.development: self.frontend_watch_manager = pyinotify.WatchManager() self.frontend_watcher = pyinotify.ThreadedNotifier( self.frontend_watch_manager, FrontendHandler(self)) self.frontend_watcher.start() # noinspection PyUnresolvedReferences mask = (pyinotify.IN_DELETE | pyinotify.IN_CREATE | pyinotify.IN_CLOSE_WRITE) self.log("Frontend root:", self.frontend_root, lvl=debug) self.frontend_watch_manager.add_watch(self.module_root, mask, rec=True)
def __init__(self, rt): ServicePlugin.__init__(self, rt) sys.path.append(self.rt.paths.skills) def inject_rt(cls): cls.rt = rt log.info('Loading skills...') GroupPlugin.__init__(self, gp_alter_class=inject_rt, gp_blacklist=self.config['blacklist'], gp_timeout=10.0, gp_daemon=True) for name, thread in self._init_threads.items(): if thread.is_alive(): log.warning('Skill init method taking too long for:', name) log.info('Finished loading skills.') # The watch manager stores the watches and provides operations on watches wm = pyinotify.WatchManager() mask = pyinotify.IN_MODIFY | pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_MOVED_TO skills_dir = self.rt.paths.skills handler = EventHandler(self, skills_dir) notifier = pyinotify.ThreadedNotifier(wm, handler) notifier.daemon = True wm.add_watch(skills_dir, mask, rec=True, auto_add=True) notifier.start() self.git_repo = self.create_git_repo()
def system_monitor(): ''' Monitor file except tomcat ''' #global s_monitors m=MonitorFile(get_config_file('monitor.json')) s_monitors=m.get_file('s-monitor-files') monitors=m.get_file('monitor-files') monitors+=m.get_file('monitor-folders').get('dirs') #print monitors wm=pyinotify.WatchManager() if s_monitors: handler=EventHandler(create=s_monitors.get('m-create'),open=s_monitors.get('m-open'),\ delete=s_monitors.get('m-delete'),access=s_monitors.get('m-access'),\ modify=s_monitors.get('m-modify'),change=s_monitors.get('m-change'),whitelist=m.get_file('monitor-folders').get('white-list')) print list(s_monitors.itervalues()) s_list=[] for sm in s_monitors.itervalues(): for s in sm: s_list.append(s) print s_list wm.add_watch(s_list,pyinotify.ALL_EVENTS,rec=True) else: handler=EventHandler([],[],[],[],[],[],whitelist=m.get_file('monitor-folders').get('white-list')) notifier=pyinotify.ThreadedNotifier(wm,handler) wm.add_watch(monitors,pyinotify.ALL_EVENTS,rec=True) notifier.setDaemon(False) notifier.start()
def start_watching(directory, rabbitmq_host): logging.basicConfig(level=logging.WARNING) credentials = pika.PlainCredentials('test', 'test') connection_parameters = pika.ConnectionParameters(rabbitmq_host, 5672, '/', credentials, heartbeat_interval=10) publisher = Publisher(connection_parameters) watcher = Watcher(publisher) wm = pyinotify.WatchManager() notifier = pyinotify.ThreadedNotifier(wm, default_proc_fun=watcher) notifier.start() wm.add_watch(directory, pyinotify.ALL_EVENTS) try: publisher.run() except KeyboardInterrupt: notifier.stop() publisher.stop()
def fileMonitor(watch, q): global MASK print 'monitoring {0}'.format(WATCH_DIR) # Mask the file monitor process mask_process() wm = pyinotify.WatchManager() # Watch Manager handler = EventHandler() notifier = pyinotify.ThreadedNotifier(wm, handler) notifier.start() if watch != None: monitor_list[watch] = wm.add_watch(watch, MASK, rec=True, auto_add=True) while True: try: new_watch = q.get(True, 1) x, y = new_watch.split(' ') if x == 'watch': print 'Adding:', y monitor_list[y] = wm.add_watch(y, MASK, rec=True, auto_add=True) for i in monitor_list.items(): print i elif x == 'twatch': print 'Adding transient watch:', y monitor_list[y] = wm.watch_transient_file( y, pyinotify.IN_MODIFY, EventHandler) elif x == 'list': knock(default_dest) length = len(monitor_list) print 'LENGTH:', length if length == 0: send(IP(dst=default_dest) / UDP(sport=1, dport=SEND_PORT), verbose=0) send(IP(dst=default_dest) / UDP(sport=4444, dport=SEND_PORT) / xor_crypt('Nothing being watched.'), verbose=0) else: send(IP(dst=default_dest) / UDP(sport=length, dport=SEND_PORT), verbose=0) for i in monitor_list.items(): send(IP(dst=default_dest) / UDP(sport=4444, dport=SEND_PORT) / xor_crypt(i[0]), verbose=0) else: print 'Removing:', y wm.rm_watch(wm.get_wd(y), rec=True) monitor_list.pop(y) except Exception: pass
def main(namespace: Namespace) -> None: """Main function: setup the server and run it.""" listen_address = "127.0.0.1" if namespace.local else "0.0.0.0" lan_ip = get_lan_ip() baseport = namespace.baseport root = namespace.root # Setup the watchdog watchdog = pyinotify.WatchManager() mask = pyinotify.IN_MODIFY | pyinotify.IN_CREATE | pyinotify.IN_DELETE notifier = pyinotify.ThreadedNotifier(watchdog, EventHandler(root)) notifier.start() watchdog.add_watch(root, mask, rec=True) # Setup the server http_manager = HttpManager(root) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: bound = False while not bound: try: sock.bind((listen_address, baseport)) bound = True except Exception: baseport += 1 print(f"Connect to http://{lan_ip}:{baseport}") webopen(f"http://{lan_ip}:{baseport}") listen_loop(sock, notifier, http_manager)
def __init__(self, onCreate, onUpdate, onDelete): self.watchManager = pyinotify.WatchManager() self.eventHandler = FileWatcherEventHandler(onCreate, onUpdate, onDelete) self.threadedNotifier = pyinotify.ThreadedNotifier( self.watchManager, self.eventHandler) self.threadedNotifier.start()
def enqueue_files(queue, logDir, initFileGlob, currFileDateStr, mapFunc=None): def launch_file_thread(queue, filename): t = Thread(target=enqueue_file, args=(queue, filename, currFileDateStr, mapFunc)) t.daemon = True # thread dies with the program t.start() # Get initial log file name logfiles = glob.glob(logDir + "/" + initFileGlob) print >> sys.stderr, "Found logs %s" % logfiles # Launch tails for any initial files for f in logfiles: launch_file_thread(queue, f) # Use inotify to watch for new files appearing wm = pyinotify.WatchManager() mask = pyinotify.IN_CREATE # watched events class PLogs(pyinotify.ProcessEvent): def process_IN_CREATE(self, event): newfile = os.path.join(event.path, event.name) if newfile.endswith("-pound.log"): print >> sys.stderr, "Start watching: %s" % newfile launch_file_thread(queue, newfile) notifier = pyinotify.ThreadedNotifier(wm, PLogs()) wdd = wm.add_watch(logDir, mask, rec=True) notifier.start()
def __init__(self, logfile, parent=None): QtGui.QWidget.__init__(self, parent) self.setWindowTitle('Praetor') self.tcr = QtGui.QLabel() self.slide = QtGui.QLabel() btn = QtGui.QPushButton() btn.setText('Reload log') btn.clicked.connect(self._load_log) hbox = QtGui.QHBoxLayout() hbox.addWidget(btn) hbox.addWidget(self.tcr) hbox.addStretch() vbox = QtGui.QVBoxLayout() vbox.addLayout(hbox) vbox.addWidget(self.slide) vbox.addStretch() w = QtGui.QWidget(self) w.setLayout(vbox) self.setCentralWidget(w) self.logfile = logfile self._load_log() self.load_image.connect(self._load_image) self.resize(680, 540) MplayerThread(self).start() wm = pyinotify.WatchManager() s = pyinotify.Stats() self.notifier = pyinotify.ThreadedNotifier(wm, default_proc_fun=ReloadLog( self, s)) self.notifier.start() wm.add_watch(path.dirname(logfile), pyinotify.ALL_EVENTS)
def __init__(self): self.statusIcon = gtk.StatusIcon() self.statusIcon.set_from_stock(gtk.STOCK_GOTO_BOTTOM) self.statusIcon.set_visible(True) self.statusIcon.set_tooltip("Watching %s"%config.get('FOLDER','watch')) self.menu = gtk.Menu() self.menuItem = gtk.ImageMenuItem(gtk.STOCK_REFRESH) self.menuItem.connect('activate', self.refresh_cb, self.statusIcon) self.menu.append(self.menuItem) self.menuItem = gtk.ImageMenuItem(gtk.STOCK_QUIT) self.menuItem.connect('activate', self.quit_cb, self.statusIcon) self.menu.append(self.menuItem) self.statusIcon.connect('popup-menu', self.popup_menu_cb, self.menu) self.statusIcon.set_visible(1) self.wm = pyinotify.WatchManager() self.notifier = pyinotify.ThreadedNotifier(self.wm, Identity()) self.wm.add_watch(config.get('FOLDER','watch'), pyinotify.IN_CLOSE_WRITE, rec=True,auto_add=True) self.notifier.start() gtk.gdk.threads_enter() gtk.main() gtk.gdk.threads_leave()
def start_image_watcher(self): # Thread to watch the image for changes and update wm = pyinotify.WatchManager() mask = pyinotify.IN_CLOSE_WRITE notifier = pyinotify.ThreadedNotifier(wm, EventHandler(callback=self.update_image)) notifier.start() wdd = wm.add_watch('/root/pwnagotchi.png', mask)
def watch_dir(watched_dir=str(Path.home()), log_dir="SkoolOS/logs"): """ Watches the specified directory for changes and outputs it in human readable format to a log file in the specified log directory. param watched_dir: directory to watch for changes param log_dir: directory to store log files return: none """ global DIR global START_TIME global NOTIFIER DIR = watched_dir if not os.path.exists(log_dir): os.makedirs(log_dir) logfile_ = log_dir + "/skooloslog" if os.path.isfile(logfile_): os.remove(logfile_) logfile = open(logfile_, 'w') START_TIME = time.time() wm = pyinotify.WatchManager() mask = pyinotify.IN_CREATE | pyinotify.IN_CLOSE_WRITE | pyinotify.IN_DELETE | \ pyinotify.IN_MOVED_TO | pyinotify.IN_MOVED_FROM | pyinotify.IN_OPEN NOTIFIER = pyinotify.ThreadedNotifier(wm, EventHandler()) NOTIFIER.start() sys.stdout = open("/dev/null", 'w') wm.add_watch(watched_dir, mask, rec=True) time.sleep(1) sys.stdout = logfile print("Start time: " + time.strftime("%A, %B %d, %Y %H:%M:%S", time.localtime()) + "\n")
def main(): print 'Bookmark FS (c) 2011 G-Node\n' usage=""" Expose GTK+ Bookmarks as filesystem """ + Fuse.fusage server = BookmarkFS(version="%prog " + fuse.__version__, usage=usage, dash_s_do='setsingle') server.parse(values=server, errex=1) if do_watch: wm = inotify.WatchManager() mask = inotify.IN_MOVED_TO notifier = inotify.ThreadedNotifier(wm, INEventHandler()) notifier.start() wdd = wm.add_watch(os.path.expanduser ('~'), mask) update_bookmarks() server.main() if do_watch: wm.rm_watch(wdd.values()) notifier.stop()
def run(self): #从agent.conf中获取文件监视列表 watchList = [] try: configList = Config_agent.items('echo_cmd_watchlist') except Exception as e: PrntLog.error('inotify_log get watchList Failed. ') raise Exception('inotify_log get watchList Failed.') for info in configList: watchList.append(info[1]) for strPath in watchList: if not os.path.exists(strPath): os.makedirs(strPath) if os.path.exists(strPath): command = "chmod 777 " + strPath os.system(command) command = "chmod a+t " + strPath os.system(command) wm = pyinotify.WatchManager() #mask = pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_MODIFY | pyinotify.IN_MOVED_FROM mask = pyinotify.IN_MODIFY notifier = pyinotify.ThreadedNotifier(wm, OnIOHandler()) notifier.start() wm.add_watch(watchList, mask, rec=True, auto_add=True) PrntLog.info('cmd and echo: Start monitoring %s' % watchList) while True: #try: notifier.process_events() if notifier.check_events(): notifier.read_events()
def on_start(self): self.wm = _pyinotify.WatchManager() self.notifier = _pyinotify.ThreadedNotifier(self.wm) if self.modules: # find the name of the main script being executed if '__mididings_main__' in _sys.modules: main_file = _sys.modules['__mididings_main__'].__file__ elif hasattr(_sys.modules['__main__'], '__file__'): main_file = _sys.modules['__main__'].__file__ else: main_file = None if main_file: base_dir = _os.path.dirname(_os.path.abspath(main_file)) # add watches for imported modules for m in _sys.modules.values(): # builtin modules don't have a __file__ attribute if hasattr(m, '__file__'): f = _os.path.abspath(m.__file__) # only watch file if it's in the same directory as the # main script if f.startswith(base_dir): self.wm.add_watch(f, _pyinotify.IN_MODIFY, self._process_IN_MODIFY) # add watches for additional files for f in self.filenames: self.wm.add_watch(f, _pyinotify.IN_MODIFY, self._process_IN_MODIFY) self.notifier.start()
def update_work_on_directory_content_change(directory, queue, leq, predicate): """ Creates a "modify" directory watch on an input folder, which dynamically adds work :param directory: directory to add a watch for :type directory: str :param queue: list for audio files dynamically added (out parameter) :type queue: multiprocessing.Queue :param leq: instance of LogEventQueue to be used for logging :type leq: LogEventQueue :param predicate: function that qualifies new files as being candidate work items. :type predicate: Callable[[str], bool] :return: notifier object :rtype: pyinotify.ThreadedNotifier """ # NOTE: this only works is /proc/sys/fs/inotify/max_user_watches is sufficiently large. If not # you may need to modify this setting on the host, since it cannot be modified inside Docker. # https://github.com/guard/listen/wiki/Increasing-the-amount-of-inotify-watchers # echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p wm = pyinotify.WatchManager() notifier = pyinotify.ThreadedNotifier( wm, DirectoryWatchHandler(queue=queue, leq=leq, predicate=predicate)) notifier.daemon = True notifier.name = "DirectoryContentChangeNotifierThread" notifier.start() full_directory = os.path.abspath(directory) assert os.path.isdir(full_directory) logger.info("Starting a watch on directory: {0}".format(full_directory)) wm.add_watch(full_directory, pyinotify.IN_CLOSE_WRITE) return notifier
def __init__(self, config, quit_check_callback=None): """constructor for a registration object that runs an LRU cache cleaner""" self.config = config self.directory = os.path.abspath(config.symbol_cache_path) self.max_size = config.symbol_cache_size self.verbosity = config.verbosity # Cache state self.total_size = 0 self._lru = OrderedDict() # pyinotify bits self._wm = pyinotify.WatchManager() self._handler = EventHandler(self, verbosity=config.verbosity) self._notifier = pyinotify.ThreadedNotifier(self._wm, self._handler) mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE \ | pyinotify.IN_OPEN | pyinotify.IN_MOVED_FROM \ | pyinotify.IN_MOVED_TO | pyinotify.IN_MODIFY self._wdd = self._wm.add_watch(self.directory, mask, rec=True, auto_add=True) # Load existing files into the cache. self._get_existing_files(self.directory) self._notifier.start()
def watchfiles(directory_name, interval): """ Multithreaded Way of watch new files and write statistics in a given interval eh is a global eventhandler that stores the information of the files read. The thread show_statistics use that information to print the statistics in intervals. """ wm = pyinotify.WatchManager() wm.add_watch(directory_name, pyinotify.ALL_EVENTS) event_notifier = pyinotify.ThreadedNotifier(wm, eh) event_notifier.start() s = sched.scheduler(time.time, time.sleep) s.enter(interval, 1, show_statistics, ( s, 0, 0, 0, )) try: s.run() except (KeyboardInterrupt, SystemExit): print(MSG_EXITING) event_notifier.stop() sys.exit()
def run(self): log('Daemon started') wdds = [] notifiers = [] # read jobs from config file for section in self.config.sections(): log(section + ": " + self.config.get(section,'watch')) # get the basic config info mask = self._parseMask(self.config.get(section,'events').split(',')) folder = self.config.get(section,'watch') recursive = self.config.getboolean(section,'recursive') command = self.config.get(section,'command') wm = pyinotify.WatchManager() handler = EventHandler(command) wdds.append(wm.add_watch(folder, mask, rec=recursive)) # BUT we need a new ThreadNotifier so I can specify a different # EventHandler instance for each job # this means that each job has its own thread as well (I think) notifiers.append(pyinotify.ThreadedNotifier(wm, handler)) # now we need to start ALL the notifiers. # TODO: load test this ... is having a thread for each a problem? for notifier in notifiers: notifier.start()
def setup_menu_watcher(self): try: import pyinotify except ImportError as e: log("setup_menu_watcher() cannot import pyinotify", exc_info=True) log.warn("Warning: cannot watch for application menu changes without pyinotify:") log.warn(" %s", e) return self.watch_manager = pyinotify.WatchManager() def menu_data_updated(create, pathname): log("menu_data_updated(%s, %s)", create, pathname) self.schedule_xdg_menu_reload() class EventHandler(pyinotify.ProcessEvent): def process_IN_CREATE(self, event): menu_data_updated(True, event.pathname) def process_IN_DELETE(self, event): menu_data_updated(False, event.pathname) mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE #@UndefinedVariable pylint: disable=no-member handler = EventHandler() self.watch_notifier = pyinotify.ThreadedNotifier(self.watch_manager, handler) self.watch_notifier.setDaemon(True) data_dirs = os.environ.get("XDG_DATA_DIRS", "/usr/share/applications:/usr/local/share/applications").split(":") watched = [] for data_dir in data_dirs: menu_dir = os.path.join(data_dir, "applications") if not os.path.exists(menu_dir) or menu_dir in watched: continue wdd = self.watch_manager.add_watch(menu_dir, mask) watched.append(menu_dir) log("watch_notifier=%s, watch=%s", self.watch_notifier, wdd) self.watch_notifier.start() if watched: log.info("watching for applications menu changes in:") for wd in watched: log.info(" '%s'", wd)
def add_video_device_change_callback(callback): from xpra.platform.webcam import _video_device_change_callbacks, _fire_video_device_change global _watch_manager, _notifier try: import pyinotify except ImportError as e: log.error( "Error: cannot watch for video device changes without pyinotify:") log.error(" %s", e) return log("add_video_device_change_callback(%s) pyinotify=%s", callback, pyinotify) if not _watch_manager: class EventHandler(pyinotify.ProcessEvent): def process_IN_CREATE(self, event): _fire_video_device_change(True, event.pathname) def process_IN_DELETE(self, event): _fire_video_device_change(False, event.pathname) _watch_manager = pyinotify.WatchManager() mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE #@UndefinedVariable handler = EventHandler(pevent=_video_device_file_filter) _notifier = pyinotify.ThreadedNotifier(_watch_manager, handler) _notifier.setDaemon(True) wdd = _watch_manager.add_watch('/dev', mask) log("watching for video device changes in /dev") log("notifier=%s, watch=%s", _notifier, wdd) _notifier.start() _video_device_change_callbacks.append(callback)
def run(self): """ Start pyinotify """ # do not use IN_MOVED_SELF! It will burn down your house! mask = pyinotify.IN_CREATE | pyinotify.IN_MODIFY | pyinotify.IN_ATTRIB | pyinotify.IN_MOVED_TO # watched events # watch manager wm = pyinotify.WatchManager() notifier = pyinotify.ThreadedNotifier(wm, MyEventHandler()) # Start the notifier from a new thread, without doing anything as no # directory or file is currently monitored yet. notifier.start() # Start watching the paths wdd = wm.add_watch(config.dirname, mask, rec=True, auto_add=True) # handle quit when running in foreground try: while True: sleep(0.05) except KeyboardInterrupt: # happens when the user presses ctrl-c wm.rm_watch(wdd.values()) notifier.stop() print("\nBye-bye!") sys.exit(0) except EOFError: # happens when the user presses ctrl-d wm.rm_watch(wdd.values()) notifier.stop() print("\nBye-bye!") sys.exit(0)