Python pyinotify.Notifier() Examples

The following are 30 code examples of pyinotify.Notifier(). 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: __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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
Source File: honggcorpusmanager.py    From ffw with GNU General Public License v3.0 5 votes vote down vote up
def start(self):
        watchPath = self.config["input_dir"]
        self.notifier = pyinotify.Notifier(self.wm, self.handler, timeout=10)
        self.wdd = self.wm.add_watch(watchPath, self.mask, rec=False) 
Example #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 #22
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 #23
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 #24
Source File: autoreload.py    From python2017 with MIT License 4 votes vote down vote up
def inotify_code_changed():
    """
    Checks for changed code using inotify. After being called
    it blocks until a change event has been fired.
    """
    class EventHandler(pyinotify.ProcessEvent):
        modified_code = None

        def process_default(self, event):
            if event.path.endswith('.mo'):
                EventHandler.modified_code = I18N_MODIFIED
            else:
                EventHandler.modified_code = FILE_MODIFIED

    wm = pyinotify.WatchManager()
    notifier = pyinotify.Notifier(wm, EventHandler())

    def update_watch(sender=None, **kwargs):
        if sender and getattr(sender, 'handles_files', False):
            # No need to update watches when request serves files.
            # (sender is supposed to be a django.core.handlers.BaseHandler subclass)
            return
        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
        )
        for path in gen_filenames(only_new=True):
            wm.add_watch(path, mask)

    # New modules may get imported when a request is processed.
    request_finished.connect(update_watch)

    # Block until an event happens.
    update_watch()
    notifier.check_events(timeout=None)
    notifier.read_events()
    notifier.process_events()
    notifier.stop()

    # If we are here the code must have changed.
    return EventHandler.modified_code 
Example #25
Source File: autoreload.py    From openhgsenti with Apache License 2.0 4 votes vote down vote up
def inotify_code_changed():
    """
    Checks for changed code using inotify. After being called
    it blocks until a change event has been fired.
    """
    class EventHandler(pyinotify.ProcessEvent):
        modified_code = None

        def process_default(self, event):
            if event.path.endswith('.mo'):
                EventHandler.modified_code = I18N_MODIFIED
            else:
                EventHandler.modified_code = FILE_MODIFIED

    wm = pyinotify.WatchManager()
    notifier = pyinotify.Notifier(wm, EventHandler())

    def update_watch(sender=None, **kwargs):
        if sender and getattr(sender, 'handles_files', False):
            # No need to update watches when request serves files.
            # (sender is supposed to be a django.core.handlers.BaseHandler subclass)
            return
        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
        )
        for path in gen_filenames(only_new=True):
            wm.add_watch(path, mask)

    # New modules may get imported when a request is processed.
    request_finished.connect(update_watch)

    # Block until an event happens.
    update_watch()
    notifier.check_events(timeout=None)
    notifier.read_events()
    notifier.process_events()
    notifier.stop()

    # If we are here the code must have changed.
    return EventHandler.modified_code 
Example #26
Source File: autoreload.py    From python with Apache License 2.0 4 votes vote down vote up
def inotify_code_changed():
    """
    Checks for changed code using inotify. After being called
    it blocks until a change event has been fired.
    """
    class EventHandler(pyinotify.ProcessEvent):
        modified_code = None

        def process_default(self, event):
            if event.path.endswith('.mo'):
                EventHandler.modified_code = I18N_MODIFIED
            else:
                EventHandler.modified_code = FILE_MODIFIED

    wm = pyinotify.WatchManager()
    notifier = pyinotify.Notifier(wm, EventHandler())

    def update_watch(sender=None, **kwargs):
        if sender and getattr(sender, 'handles_files', False):
            # No need to update watches when request serves files.
            # (sender is supposed to be a django.core.handlers.BaseHandler subclass)
            return
        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
        )
        for path in gen_filenames(only_new=True):
            wm.add_watch(path, mask)

    # New modules may get imported when a request is processed.
    request_finished.connect(update_watch)

    # Block until an event happens.
    update_watch()
    notifier.check_events(timeout=None)
    notifier.read_events()
    notifier.process_events()
    notifier.stop()

    # If we are here the code must have changed.
    return EventHandler.modified_code 
Example #27
Source File: autoreload.py    From Hands-On-Application-Development-with-PyCharm with MIT License 4 votes vote down vote up
def inotify_code_changed():
    """
    Check for changed code using inotify. After being called
    it blocks until a change event has been fired.
    """
    class EventHandler(pyinotify.ProcessEvent):
        modified_code = None

        def process_default(self, event):
            if event.path.endswith('.mo'):
                EventHandler.modified_code = I18N_MODIFIED
            else:
                EventHandler.modified_code = FILE_MODIFIED

    wm = pyinotify.WatchManager()
    notifier = pyinotify.Notifier(wm, EventHandler())

    def update_watch(sender=None, **kwargs):
        if sender and getattr(sender, 'handles_files', False):
            # No need to update watches when request serves files.
            # (sender is supposed to be a django.core.handlers.BaseHandler subclass)
            return
        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
        )
        for path in gen_filenames(only_new=True):
            wm.add_watch(path, mask)

    # New modules may get imported when a request is processed.
    request_finished.connect(update_watch)

    # Block until an event happens.
    update_watch()
    notifier.check_events(timeout=None)
    notifier.read_events()
    notifier.process_events()
    notifier.stop()

    # If we are here the code must have changed.
    return EventHandler.modified_code 
Example #28
Source File: runas2daemon.py    From pyas2 with GNU General Public License v2.0 4 votes vote down vote up
def linux_event_handler(logger, dir_watch_data, cond, tasks):
        watch_manager = pyinotify.WatchManager()
        mask = pyinotify.IN_CLOSE_WRITE | pyinotify.IN_MOVED_TO | pyinotify.IN_MODIFY | pyinotify.IN_CREATE
        for dir_watch in dir_watch_data:
            logger.info(_(u'Watching directory %s' % dir_watch['path']))
            watch_manager.add_watch(path=dir_watch['path'], mask=mask, rec=False, auto_add=True, do_glob=True)
        handler = LinuxEventHandler(logger=logger, dir_watch_data=dir_watch_data, cond=cond, tasks=tasks)
        notifier = pyinotify.Notifier(watch_manager, handler)
        notifier.loop()
        # end of linux-specific ################################################################################## 
Example #29
Source File: autoreload.py    From bioforum with MIT License 4 votes vote down vote up
def inotify_code_changed():
    """
    Check for changed code using inotify. After being called
    it blocks until a change event has been fired.
    """
    class EventHandler(pyinotify.ProcessEvent):
        modified_code = None

        def process_default(self, event):
            if event.path.endswith('.mo'):
                EventHandler.modified_code = I18N_MODIFIED
            else:
                EventHandler.modified_code = FILE_MODIFIED

    wm = pyinotify.WatchManager()
    notifier = pyinotify.Notifier(wm, EventHandler())

    def update_watch(sender=None, **kwargs):
        if sender and getattr(sender, 'handles_files', False):
            # No need to update watches when request serves files.
            # (sender is supposed to be a django.core.handlers.BaseHandler subclass)
            return
        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
        )
        for path in gen_filenames(only_new=True):
            wm.add_watch(path, mask)

    # New modules may get imported when a request is processed.
    request_finished.connect(update_watch)

    # Block until an event happens.
    update_watch()
    notifier.check_events(timeout=None)
    notifier.read_events()
    notifier.process_events()
    notifier.stop()

    # If we are here the code must have changed.
    return EventHandler.modified_code 
Example #30
Source File: autoreload.py    From GTDWeb with GNU General Public License v2.0 4 votes vote down vote up
def inotify_code_changed():
    """
    Checks for changed code using inotify. After being called
    it blocks until a change event has been fired.
    """
    class EventHandler(pyinotify.ProcessEvent):
        modified_code = None

        def process_default(self, event):
            if event.path.endswith('.mo'):
                EventHandler.modified_code = I18N_MODIFIED
            else:
                EventHandler.modified_code = FILE_MODIFIED

    wm = pyinotify.WatchManager()
    notifier = pyinotify.Notifier(wm, EventHandler())

    def update_watch(sender=None, **kwargs):
        if sender and getattr(sender, 'handles_files', False):
            # No need to update watches when request serves files.
            # (sender is supposed to be a django.core.handlers.BaseHandler subclass)
            return
        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
        )
        for path in gen_filenames(only_new=True):
            wm.add_watch(path, mask)

    # New modules may get imported when a request is processed.
    request_finished.connect(update_watch)

    # Block until an event happens.
    update_watch()
    notifier.check_events(timeout=None)
    notifier.read_events()
    notifier.process_events()
    notifier.stop()

    # If we are here the code must have changed.
    return EventHandler.modified_code