Python pyinotify.WatchManager() Examples

The following are 30 code examples of pyinotify.WatchManager(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyinotify , or try the search function .
Example #1
Source File: run_server.py    From DevOpsCloud with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #2
Source File: __main__.py    From edx-xapi-bridge with Apache License 2.0 6 votes vote down vote up
def watch(watch_file):
	'''
	Watch the given file for changes
	'''
	
	wm = WatchManager()

	with TailHandler(watch_file) as th:

		notifier = Notifier(wm, th)
		wdd = wm.add_watch(watch_file, TailHandler.MASK)

		notifier.loop()

		# flush queue before exiting
		th.publish_queue.publish()


	print 'Exiting' 
Example #3
Source File: configwatcher.py    From piSociEty with GNU General Public License v3.0 5 votes vote down vote up
def start_config_watch(self):
        wm = pyinotify.WatchManager()
        wm.add_watch('./config/mitmf.conf', pyinotify.IN_MODIFY)
        notifier = pyinotify.Notifier(wm, self)
        
        t = threading.Thread(name='ConfigWatcher', target=notifier.loop)
        t.setDaemon(True)
        t.start() 
Example #4
Source File: filewatch.py    From doit with MIT License 5 votes vote down vote up
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 | pyinotify.IN_MOVED_TO
        for watch_this in self.watch_dirs:
            watch_manager.add_watch(watch_this, mask)

        notifier.loop(loop_callback) 
Example #5
Source File: nameTools.py    From IntraArchiveDeduplicator with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def startDirObservers(self, useObservers=True):
		# Observers do not need to be started for simple use, particularly
		# for quick-scripts where the filesystem is not expected to change significantly.
		# Pass useObservers=False to avoid the significant delay
		# in allocating directory observers.


		self.notifierRunning = True
		# Used to check that the directories have been loaded.
		# Should probably be broken up into `notifierRunning` and `dirsLoaded` flags.

		if useObservers:
			if not "wm" in self.__dict__:
				self.wm = pyinotify.WatchManager(exclude_filter=lambda p: os.path.isfile(p))
				self.eventH = EventHandler([item["dir"] for item in self.paths.values()])
				self.notifier = pyinotify.ThreadedNotifier(self.wm, self.eventH)

			self.log.info("Setting up filesystem observers")
			for key in self.paths.keys():
				if not "observer" in self.paths[key]:
					self.log.info("Instantiating observer for path %s", self.paths[key]["dir"])

					self.paths[key]["observer"] = self.wm.add_watch(self.paths[key]["dir"], MONITORED_FS_EVENTS, rec=True)


				else:
					self.log.info("WARNING = DirNameProxy Instantiated multiple times!")

			self.notifier.start()
			self.log.info("Filesystem observers initialized")
			self.log.info("Loading DirLookup")
		else:
			self.eventH = EventHandler([item["dir"] for item in self.paths.values()])

		self.checkUpdate(force=True)
		baseDictKeys = list(self._dirDicts.keys())
		baseDictKeys.sort() 
Example #6
Source File: watch.py    From pyrocore with GNU General Public License v2.0 5 votes vote down vote up
def setup(self):
        """ Set up inotify manager.

            See https://github.com/seb-m/pyinotify/.
        """
        if not pyinotify.WatchManager:
            raise error.UserError("You need to install 'pyinotify' to use %s (%s)!" % (
                self.__class__.__name__, pyinotify._import_error)) # pylint: disable=E1101, W0212

        self.manager = pyinotify.WatchManager()
        self.handler = TreeWatchHandler(job=self)
        self.notifier = pyinotify.AsyncNotifier(self.manager, self.handler)

        if self.LOG.isEnabledFor(logging.DEBUG):
            mask = pyinotify.ALL_EVENTS
        else:
            mask = pyinotify.IN_CLOSE_WRITE | pyinotify.IN_MOVED_TO # bogus pylint: disable=E1101

        # Add all configured base dirs
        for path in self.config.path:
            self.manager.add_watch(path.strip(), mask, rec=True, auto_add=True) 
Example #7
Source File: monitor.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, listener):
        threading.Thread.__init__(self)
        self.__p = Processor(self, listener)
        self.manager = WatchManager()
        self.notifier = Notifier(self.manager, self.__p)
        self.event = threading.Event()
        self.setDaemon(True)
        self.watches = []
        self.__isSuspended = False 
Example #8
Source File: configwatcher.py    From MITMf with GNU General Public License v3.0 5 votes vote down vote up
def start_config_watch(self):
        wm = pyinotify.WatchManager()
        wm.add_watch('./config/mitmf.conf', pyinotify.IN_MODIFY)
        notifier = pyinotify.Notifier(wm, self)
        
        t = threading.Thread(name='ConfigWatcher', target=notifier.loop)
        t.setDaemon(True)
        t.start() 
Example #9
Source File: desktop_parser.py    From opensnitch with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        self.running = True
        wm = pyinotify.WatchManager()
        notifier = pyinotify.Notifier(wm)

        def inotify_callback(event):
            if event.mask == pyinotify.IN_CLOSE_WRITE:
                self._parse_desktop_file(event.pathname)

            elif event.mask == pyinotify.IN_DELETE:
                with self.lock:
                    for cmd, data in self.apps.items():
                        if data[2] == event.pathname:
                            del self.apps[cmd]
                            break

        for p in DESKTOP_PATHS:
            if os.path.exists(p):
                wm.add_watch(p,
                             pyinotify.IN_CLOSE_WRITE | pyinotify.IN_DELETE,
                             inotify_callback)
        notifier.loop() 
Example #10
Source File: watcher.py    From django-livereload-server with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        Watcher.__init__(self)

        self.wm = pyinotify.WatchManager()
        self.notifier = None
        self.callback = None 
Example #11
Source File: FileWatcher.py    From bcloud with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, monitor_path, bcloud_app):

        super(WatchFileChange, self).__init__()
        self.setDaemon(True) 
        self.monitor_path = monitor_path 
        self.bcloud_app = bcloud_app
        self.submitter = TaskSubmitter(self.bcloud_app)
        self.submitter.start()
        self.handler = EventHandler(self.monitor_path, self.bcloud_app,
                                    self.submitter)
        self.wm = pyinotify.WatchManager()
        self.wdds = self.wm.add_watch(self.monitor_path, MASK, rec=True,
                                      auto_add=True)
        self.notifyer = pyinotify.Notifier(self.wm, self.handler) 
Example #12
Source File: watchers.py    From oslo.log with Apache License 2.0 5 votes vote down vote up
def _watch_file(self):
        mask = pyinotify.IN_MOVED_FROM | pyinotify.IN_DELETE
        watch_manager = pyinotify.WatchManager()
        handler = _FileKeeper(watched_handler=self,
                              watched_file=self._log_file)
        notifier = _EventletThreadedNotifier(
            watch_manager,
            default_proc_fun=handler,
            read_freq=FastWatchedFileHandler.READ_FREQ,
            timeout=FastWatchedFileHandler.TIMEOUT)
        notifier.daemon = True
        watch_manager.add_watch(self._log_dir, mask)
        notifier.start() 
Example #13
Source File: cryptopuck.py    From cryptopuck with Apache License 2.0 5 votes vote down vote up
def main():
    parser_description = "Cryptopuck: Encrypt your drives on the fly"
    parser = argparse.ArgumentParser(description=parser_description)
    parser.add_argument("--mountpoint",
                        help="Path to where new volumes are mounted",
                        required=True)
    parser.add_argument("--public-key",
                        help="Path to the public key", required=True)
    args = parser.parse_args()

    if not os.path.isdir(args.mountpoint):
        print("Mountpoint does not exist or not a directory:", args.mountpoint)
        sys.exit(1)

    # Setup the Led Manager
    main_thread = threading.current_thread()
    led_manager = LedManager(main_thread)
    led_thread = threading.Thread(target=led_manager.run)
    led_thread.start()

    # Setup pyInotify
    wm = pyinotify.WatchManager()  # Watch Manager
    mask = pyinotify.IN_CREATE  # watched events

    notifier = pyinotify.Notifier(wm, EventHandler(args.public_key,
                                  led_manager))
    wdd = wm.add_watch(args.mountpoint, mask)

    notifier.loop()  # Blocking loop
    led_thread.join() 
Example #14
Source File: watcher.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def __init__(self):
        Watcher.__init__(self)

        self.wm = pyinotify.WatchManager()
        self.notifier = None
        self.callback = None 
Example #15
Source File: watchers.py    From paasta with Apache License 2.0 5 votes vote down vote up
def __init__(
        self,
        instances_to_bounce: DelayDeadlineQueueProtocol,
        cluster: str,
        config: SystemPaastaConfig,
        **kwargs: Any,
    ) -> None:
        super().__init__(instances_to_bounce, cluster, config)
        self.wm = pyinotify.WatchManager()
        self.wm.add_watch(PATH_TO_SYSTEM_PAASTA_CONFIG_DIR, self.mask, rec=True)
        self.notifier = pyinotify.Notifier(
            watch_manager=self.wm,
            default_proc_fun=PublicConfigEventHandler(filewatcher=self),
        ) 
Example #16
Source File: watchers.py    From paasta with Apache License 2.0 5 votes vote down vote up
def __init__(
        self,
        instances_to_bounce: DelayDeadlineQueueProtocol,
        cluster: str,
        config: SystemPaastaConfig,
        **kwargs: Any,
    ) -> None:
        super().__init__(instances_to_bounce, cluster, config)
        self.wm = pyinotify.WatchManager()
        self.wm.add_watch(DEFAULT_SOA_DIR, self.mask, rec=True)
        self.notifier = pyinotify.Notifier(
            watch_manager=self.wm,
            default_proc_fun=YelpSoaEventHandler(filewatcher=self),
        ) 
Example #17
Source File: file_monitor.py    From pytos with Apache License 2.0 5 votes vote down vote up
def __init__(self, file_paths, watch_mask=FILE_CHANGE_MASK):
        self.inotify_watch_manager = pyinotify.WatchManager()
        self._file_paths = file_paths
        self._event_handler = ModifiedFileEventHandler(callback=self._reload_modified_file)
        self._inotify_notifier = pyinotify.Notifier(self.inotify_watch_manager, default_proc_fun=self._event_handler)
        self._loop_thread = threading.Thread(target=self._inotify_notifier.loop, daemon=True)
        for file_path in self._file_paths:
            self.inotify_watch_manager.add_watch(file_path, watch_mask)
        self._loop_thread.start()
        atexit.register(self._shutdown) 
Example #18
Source File: fs_change_linux.py    From marsnake with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, file_created_captured, file_modified_captured):
		self.WATCHDIR = u'/tmp'
		
		self.file_created_captured = file_created_captured
		self.file_modified_captured = file_modified_captured
		
		self.wm = pyinotify.WatchManager()  # Watch Manager
		self.mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE  | pyinotify.IN_MODIFY # watched events
		
		self.notifier = pyinotify.Notifier(self.wm, self)
		self.wdd = self.wm.add_watch(self.WATCHDIR, self.mask, rec = True) 
Example #19
Source File: monitor.py    From hacker-scripts with MIT License 5 votes vote down vote up
def main():
    (options, args) = parser.parse_args()
    if None in [options.watch_dir, options.backup_dir]:
        parser.print_help()
        return

    # 删除最后的 /
    options.watch_dir = options.watch_dir.rstrip('/')
    options.backup_dir = options.backup_dir.rstrip('/')

    global watch_dir_name
    global back_dir_name
    watch_dir_name = options.watch_dir
    back_dir_name = options.backup_dir

    logger.info('watch dir %s' % options.watch_dir)
    logger.info('back  dir %s' % options.backup_dir)

    if not options.disable_backup:
        backup_monitor_dir(options.watch_dir, options.backup_dir)

    # watch manager
    wm = pyinotify.WatchManager()
    wm.add_watch(options.watch_dir, pyinotify.ALL_EVENTS, rec=True)
    wm.add_watch(options.backup_dir, pyinotify.ALL_EVENTS, rec=True)

    # event handler
    eh = FileEventHandler()

    # notifier
    notifier = pyinotify.Notifier(wm, eh)
    notifier.loop() 
Example #20
Source File: autoreload.py    From pysoa with Apache License 2.0 5 votes vote down vote up
def code_changed(self):
        notify_mask = (
            pyinotify.IN_MODIFY |
            pyinotify.IN_DELETE |
            pyinotify.IN_ATTRIB |
            pyinotify.IN_MOVED_FROM |
            pyinotify.IN_MOVED_TO |
            pyinotify.IN_CREATE |
            pyinotify.IN_DELETE_SELF |
            pyinotify.IN_MOVE_SELF
        )

        class EventHandler(pyinotify.ProcessEvent):
            def process_default(self, event):
                pass

        watch_manager = pyinotify.WatchManager()
        self.notifier = pyinotify.Notifier(watch_manager, EventHandler())

        file_names = self.get_watch_file_names(only_new=True)

        for file_name in file_names:
            watch_manager.add_watch(file_name, notify_mask)

        self.notifier.check_events(timeout=None)
        if self.watching:
            self.notifier.read_events()
            self.notifier.process_events()
            self.notifier.stop()
            self.notifier = None

            # If we are here, then one or more files must have changed
            return True

        return False 
Example #21
Source File: honggcorpusmanager.py    From ffw with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, config, corpusManager):
        self.wm = pyinotify.WatchManager()
        self.mask = pyinotify.IN_CREATE
        self.handler = FileWatcherEventHandler(corpusManager)
        self.wdd = None
        self.config = config 
Example #22
Source File: serving.py    From Flask with Apache License 2.0 4 votes vote down vote up
def _reloader_inotify(extra_files=None, interval=None):
    # Mutated by inotify loop when changes occur.
    changed = [False]

    # Setup inotify watches
    from pyinotify import WatchManager, Notifier

    # this API changed at one point, support both
    try:
        from pyinotify import EventsCodes as ec
        ec.IN_ATTRIB
    except (ImportError, AttributeError):
        import pyinotify as ec

    wm = WatchManager()
    mask = ec.IN_DELETE_SELF | ec.IN_MOVE_SELF | ec.IN_MODIFY | ec.IN_ATTRIB

    def signal_changed(event):
        if changed[0]:
            return
        _log('info', ' * Detected change in %r, reloading' % event.path)
        changed[:] = [True]

    for fname in extra_files or ():
        wm.add_watch(fname, mask, signal_changed)

    # ... And now we wait...
    notif = Notifier(wm)
    try:
        while not changed[0]:
            # always reiterate through sys.modules, adding them
            for fname in _iter_module_files():
                wm.add_watch(fname, mask, signal_changed)
            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)


# currently we always use the stat loop reloader for the simple reason
# that the inotify one does not respond to added files properly.  Also
# it's quite buggy and the API is a mess. 
Example #23
Source File: serving.py    From Werkzeug-docs-cn with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def _reloader_inotify(extra_files=None, interval=None):
    # Mutated by inotify loop when changes occur.
    changed = [False]

    # Setup inotify watches
    from pyinotify import WatchManager, Notifier

    # this API changed at one point, support both
    try:
        from pyinotify import EventsCodes as ec
        ec.IN_ATTRIB
    except (ImportError, AttributeError):
        import pyinotify as ec

    wm = WatchManager()
    mask = ec.IN_DELETE_SELF | ec.IN_MOVE_SELF | ec.IN_MODIFY | ec.IN_ATTRIB

    def signal_changed(event):
        if changed[0]:
            return
        _log('info', ' * Detected change in %r, reloading' % event.path)
        changed[:] = [True]

    for fname in extra_files or ():
        wm.add_watch(fname, mask, signal_changed)

    # ... And now we wait...
    notif = Notifier(wm)
    try:
        while not changed[0]:
            # always reiterate through sys.modules, adding them
            for fname in _iter_module_files():
                wm.add_watch(fname, mask, signal_changed)
            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)


# currently we always use the stat loop reloader for the simple reason
# that the inotify one does not respond to added files properly.  Also
# it's quite buggy and the API is a mess. 
Example #24
Source File: __main__.py    From recursive-gobuster with MIT License 4 votes vote down vote up
def main(args_ns: argparse.Namespace) -> None:
    tmpdir = tempfile.mkdtemp(prefix="rcrsv-gbstr")  # directory for gobuster scan results

    # watch manager stores the watches and provides operations on watches
    wm = pyinotify.WatchManager()

    version = get_gobuster_version()

    handler = EventHandler(
        target=args_ns.target,
        tmpdir=tmpdir,
        wordlist=args_ns.wordlist,
        threads=args_ns.threads,
        extensions=args_ns.extensions,
        devnull=args.devnull,
        user=args_ns.user,
        password=args_ns.password,
        proxy=args_ns.proxy,
        version=version,
        status=args_ns.status,
    )

    notifier = pyinotify.Notifier(wm, handler)

    # watch for file appends (found dir/file) and files closing (scan complete)
    mask = pyinotify.IN_MODIFY | pyinotify.IN_CLOSE_WRITE

    wm.add_watch(tmpdir, mask)

    handler.run_gobuster(args_ns.target)  # kick off first scan against initial target

    signal.signal(signal.SIGINT, handler.cleanup)  # register signal handler to handle SIGINT

    notifier.loop() 
Example #25
Source File: serving.py    From appengine-try-python-flask with Apache License 2.0 4 votes vote down vote up
def _reloader_inotify(extra_files=None, interval=None):
    # Mutated by inotify loop when changes occur.
    changed = [False]

    # Setup inotify watches
    from pyinotify import WatchManager, Notifier

    # this API changed at one point, support both
    try:
        from pyinotify import EventsCodes as ec
        ec.IN_ATTRIB
    except (ImportError, AttributeError):
        import pyinotify as ec

    wm = WatchManager()
    mask = ec.IN_DELETE_SELF | ec.IN_MOVE_SELF | ec.IN_MODIFY | ec.IN_ATTRIB

    def signal_changed(event):
        if changed[0]:
            return
        _log('info', ' * Detected change in %r, reloading' % event.path)
        changed[:] = [True]

    for fname in extra_files or ():
        wm.add_watch(fname, mask, signal_changed)

    # ... And now we wait...
    notif = Notifier(wm)
    try:
        while not changed[0]:
            # always reiterate through sys.modules, adding them
            for fname in _iter_module_files():
                wm.add_watch(fname, mask, signal_changed)
            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)


# currently we always use the stat loop reloader for the simple reason
# that the inotify one does not respond to added files properly.  Also
# it's quite buggy and the API is a mess. 
Example #26
Source File: serving.py    From Flask with Apache License 2.0 4 votes vote down vote up
def _reloader_inotify(extra_files=None, interval=None):
    # Mutated by inotify loop when changes occur.
    changed = [False]

    # Setup inotify watches
    from pyinotify import WatchManager, Notifier

    # this API changed at one point, support both
    try:
        from pyinotify import EventsCodes as ec
        ec.IN_ATTRIB
    except (ImportError, AttributeError):
        import pyinotify as ec

    wm = WatchManager()
    mask = ec.IN_DELETE_SELF | ec.IN_MOVE_SELF | ec.IN_MODIFY | ec.IN_ATTRIB

    def signal_changed(event):
        if changed[0]:
            return
        _log('info', ' * Detected change in %r, reloading' % event.path)
        changed[:] = [True]

    for fname in extra_files or ():
        wm.add_watch(fname, mask, signal_changed)

    # ... And now we wait...
    notif = Notifier(wm)
    try:
        while not changed[0]:
            # always reiterate through sys.modules, adding them
            for fname in _iter_module_files():
                wm.add_watch(fname, mask, signal_changed)
            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)


# currently we always use the stat loop reloader for the simple reason
# that the inotify one does not respond to added files properly.  Also
# it's quite buggy and the API is a mess. 
Example #27
Source File: serving.py    From arithmancer with Apache License 2.0 4 votes vote down vote up
def _reloader_inotify(extra_files=None, interval=None):
    # Mutated by inotify loop when changes occur.
    changed = [False]

    # Setup inotify watches
    from pyinotify import WatchManager, Notifier

    # this API changed at one point, support both
    try:
        from pyinotify import EventsCodes as ec
        ec.IN_ATTRIB
    except (ImportError, AttributeError):
        import pyinotify as ec

    wm = WatchManager()
    mask = ec.IN_DELETE_SELF | ec.IN_MOVE_SELF | ec.IN_MODIFY | ec.IN_ATTRIB

    def signal_changed(event):
        if changed[0]:
            return
        _log('info', ' * Detected change in %r, reloading' % event.path)
        changed[:] = [True]

    for fname in extra_files or ():
        wm.add_watch(fname, mask, signal_changed)

    # ... And now we wait...
    notif = Notifier(wm)
    try:
        while not changed[0]:
            # always reiterate through sys.modules, adding them
            for fname in _iter_module_files():
                wm.add_watch(fname, mask, signal_changed)
            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)


# currently we always use the stat loop reloader for the simple reason
# that the inotify one does not respond to added files properly.  Also
# it's quite buggy and the API is a mess. 
Example #28
Source File: serving.py    From cloud-playground with Apache License 2.0 4 votes vote down vote up
def _reloader_inotify(extra_files=None, interval=None):
    # Mutated by inotify loop when changes occur.
    changed = [False]

    # Setup inotify watches
    from pyinotify import WatchManager, Notifier

    # this API changed at one point, support both
    try:
        from pyinotify import EventsCodes as ec
        ec.IN_ATTRIB
    except (ImportError, AttributeError):
        import pyinotify as ec

    wm = WatchManager()
    mask = ec.IN_DELETE_SELF | ec.IN_MOVE_SELF | ec.IN_MODIFY | ec.IN_ATTRIB

    def signal_changed(event):
        if changed[0]:
            return
        _log('info', ' * Detected change in %r, reloading' % event.path)
        changed[:] = [True]

    for fname in extra_files or ():
        wm.add_watch(fname, mask, signal_changed)

    # ... And now we wait...
    notif = Notifier(wm)
    try:
        while not changed[0]:
            # always reiterate through sys.modules, adding them
            for fname in _iter_module_files():
                wm.add_watch(fname, mask, signal_changed)
            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)


# currently we always use the stat loop reloader for the simple reason
# that the inotify one does not respond to added files properly.  Also
# it's quite buggy and the API is a mess. 
Example #29
Source File: torrents.py    From putio-automator with MIT License 4 votes vote down vote up
def watch(parent_id=None, mount=False):
    "Watch a folder for new torrents to add"

    if parent_id == None:
        parent_id = app.config.get('PUTIO_ROOT', 0)
    if mount and not os.path.exists(app.config['TORRENTS']):
        subprocess.call([
            'mount',
            '-a'
        ])

    add()

    class EventHandler(pyinotify.ProcessEvent):
        "Event handler for responding to a new or updated torrent file"
        def process_IN_CLOSE_WRITE(self, event):
            "Do the above"
            app.logger.debug('adding torrent, received event: %s' % event)
            transfer = app.client.Transfer.add_torrent(event.pathname, parent_id=parent_id)
            os.unlink(event.pathname)
            app.logger.info('added transfer: %s' % transfer)

    watch_manager = pyinotify.WatchManager()
    mask = pyinotify.IN_CLOSE_WRITE

    handler = EventHandler()
    notifier = pyinotify.Notifier(watch_manager, handler)

    wdd = watch_manager.add_watch(app.config['TORRENTS'], mask, rec=True)
    app.logger.debug('added watch: %s' % wdd)

    notifier.loop() 
Example #30
Source File: dyode_in.py    From dyode with GNU General Public License v3.0 4 votes vote down vote up
def watch_folder(properties):
    log.debug('Function "folder" launched with params %s: ' % properties)

    # inotify kernel watchdog stuff
    wm = pyinotify.WatchManager()
    mask = pyinotify.IN_CLOSE_WRITE
    notifier = pyinotify.AsyncNotifier(wm, EventHandler())
    wdd = wm.add_watch(properties['in'], mask, rec = True)
    log.debug('watching :: %s' % properties['in'])
    asyncore.loop()