def mac_fs_events_runner(root, callback): monitor_mask = ( fsevents.IN_MODIFY | fsevents.IN_CREATE | fsevents.IN_DELETE | fsevents.IN_MOVED_FROM | fsevents.IN_MOVED_TO ) def set_callback_event(event): if event.mask & monitor_mask and event.name.endswith(CHECK_EXTS): files.append(event.name) callback_event.set() elif event.mask & fsevents.IN_DELETE \ and os.path.basename(event.name) == '.noseids': callback_event.set() files = [] callback_event = threading.Event() stream = fsevents.Stream(set_callback_event, root, file_events=True) observer = fsevents.Observer() observer.schedule(stream) observer.start() callback_event.set() # set initially to invoke callback immediately try: while True: if callback_event.wait(5): callback_event.clear() testfiles, files = files, [] callback(testfiles) except: observer.unschedule(stream) observer.stop() observer.join()
def _generate_observer(self): observer = fsevents.Observer() # use file_events=True to mimic other implementations for path in self.paths: stream = fsevents.Stream(self._callback, path, file_events=True) observer.schedule(stream) return observer
def startReplicaMon(replica, fspath, path): global replicas, observer if not replica in replicas: # Ensure fspath has trailing slash. fspath = os.path.join(fspath, "") if _in_debug: _debug("start monitoring of replica [" + replica + "] [" + fspath + "]") def replicaFileEventCallback(path, mask): try: if not path.startswith(fspath): return warn("unexpected file event at path [" + path + "] for [" + fspath + "]") local_path = path[len(fspath):] local_path_toks = pathTokenize(local_path) if _in_debug: _debug("replica:[" + replica + "] file event @[" + local_path + "] (" + path + ")") triggerReplica(replica, local_path_toks) except Exception as e: # Because python is a horrible language it has a special behavior for non-main threads that # fails to catch an exception. Instead of crashing the process, only the thread is destroyed. # We fix this with this catch all exception handler. sys.stderr.write(format_exception(e)) sys.stderr.flush() os._exit(1) try: # OS X has no interface for "file level" events. You would have to implement this manually in userspace, # and compare against a snapshot. This means there's no point in us doing it, better leave it to Unison. if _in_debug: _debug("replica:[" + replica + "] watching path [" + fspath + "]") stream = fsevents.Stream(replicaFileEventCallback, fspath) observer.schedule(stream) except (FileNotFoundError, NotADirectoryError) as e: sendError(str(e)) replicas[replica] = {"stream": stream, "fspath": fspath} sendAck() while True: [cmd, args] = recvCmd() if cmd == "DIR": sendAck() elif cmd == "LINK": sendError( "link following is not supported by unison-watchdog, please disable this option (-links)" ) elif cmd == "DONE": return else: sendError("unexpected cmd in replica start: " + cmd)
def start(self): if self.immediate: run_subprocess(self.quite, self.params) if self.extensions: # observe explicit file extensions callback = fileCallbackFactory(self.extensions, self.quite, *self.params) else: # observe everything in the directory callback = directoryCallbackFactory(self.quite, *self.params) self.observer = fsevents.Observer() self.observer.start() file_events = bool(self.extensions) self.stream = fsevents.Stream(callback, self.path, file_events=file_events) self.observer.schedule(self.stream) self._is_running = True atexit.register(self.stop)
global timer # Ignore changes to Vim swap files if re.match('\..*\.swp', os.path.basename(file_event.name)): return if timer and timer.is_alive(): timer.cancel() timer = threading.Timer(0.1, schedule_sync) timer.start() # ------------------------------------------------------------------------------ # TODO: Figure out why moving this stuff into the if block doesn't work observer = fsevents.Observer() observer.start() stream = fsevents.Stream(fs_event_callback, PATH, file_events=True) observer.schedule(stream) if __name__ == '__main__': sync() queue_processor = threading.Thread(target=process_queue, args=[queue]) queue_processor.run() observer.run()
if __name__ == '__main__': options = parser.parse_args() ignored_local_paths = generate_ignored_local_paths(options) logging.info('Night gathers, and now my watch begins.') syncer = Syncer(options) syncer.start() try: import fsevents logging.info("Using fsevents.") observer = fsevents.Observer() stream = fsevents.Stream( functools.partial(file_changed, syncer.add_event, options, ignored_local_paths), options.source) observer.schedule(stream) observer.run() except ImportError: from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler logging.info("\033[91m WARNING: Using watchdog!!!\033[0m") logging.info("\033[91m Watchdog will consume your CPU and drain your battery. " "To fix, type: sudo pip install macfsevents\033[0m") class FileChangedHandler(FileSystemEventHandler): """Logs all the events captured.""" def __init__(self, syncer): self.syncer = syncer
def main(): try: opts, args = getopt.getopt(sys.argv[1:], "hv", ["help", "verbose"]) except: print str(err) usage() sys.exit(2) # e.g.: $ slushbox ~/foo/bar.html print args, opts if len(args) >= 2: command = args[0] f = os.path.abspath(args[1]) if not os.path.exists(f): raise Exception("%s was not found." % (f)) if os.path.isfile(f): directory = os.path.dirname(f) elif os.path.isdir(f): directory = os.path.abspath(f) else: usage() sys.exit(2) for o, a in opts: print "current", o, a if o in ("-h", "--help"): usage() sys.exit(0) else: assert False, "unhandled option" if command is None: raise Exception( "Specficy either a script or a command to be run, but not both" ) callback = functools.partial(run_command, command) stream = fsevents.Stream(callback, directory, file_events=True) observer = fsevents.Observer() observer.schedule(stream) observer.start() try: while True: time.sleep(5) # Make sure all files we wanted still exist, or leave if not os.path.exists(f): observer.stop() # End program if thread raises exception. if not observer.isAlive(): break # Otherwise end program by checking for ^C with KeyboardInterrupt. except (KeyboardInterrupt, OSError, IOError): observer.stop() observer.unschedule(stream) observer.join()