How to use the watchdog.events.FileSystemEventHandler function in watchdog

To help you get started, we’ve selected a few watchdog examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github gorakhargosh / watchdog / tests / legacy / test_watchdog_events.py View on Github external
all_events = [
            dir_mod_event,
            dir_del_event,
            dir_cre_event,
            dir_mov_event,
            file_mod_event,
            file_del_event,
            file_cre_event,
            file_mov_event,
        ]

        def assert_equal(a, b):
            self.assertEqual(a, b)

        class TestableEventHandler(FileSystemEventHandler):

            def on_any_event(self, event):
                assert True

            def on_modified(self, event):
                assert_equal(event.event_type, EVENT_TYPE_MODIFIED)

            def on_deleted(self, event):
                assert_equal(event.event_type, EVENT_TYPE_DELETED)

            def on_moved(self, event):
                assert_equal(event.event_type, EVENT_TYPE_MOVED)

            def on_created(self, event):
                assert_equal(event.event_type, EVENT_TYPE_CREATED)
github sdementen / piecash / pavement.py View on Github external
def doc_watch():
    """Watch for changes in the docs and rebuild HTML docs when changed."""
    try:
        from watchdog.events import FileSystemEventHandler
        from watchdog.observers import Observer
    except ImportError:
        print_failure_message('Install the watchdog package to use this task, '
                              "i.e., `pip install watchdog'.")
        raise SystemExit(1)

    class RebuildDocsEventHandler(FileSystemEventHandler):
        def __init__(self, base_paths):
            self.base_paths = base_paths

        def dispatch(self, event):
            """Dispatches events to the appropriate methods.
            :param event: The event object representing the file system event.
            :type event: :class:`watchdog.events.FileSystemEvent`
            """
            for base_path in self.base_paths:
                if event.src_path.endswith(base_path):
                    super(RebuildDocsEventHandler, self).dispatch(event)
                    # We found one that matches. We're done.
                    return

        def on_modified(self, event):
            print_failure_message('Modification detected. Rebuilding docs.')
github MatthieuDartiailh / HQCMeas / hqc_meas / tasks / manager / plugin.py View on Github external
else:
                            aux += ' ' + char
                    else:
                        if name[i+1].islower():
                            aux += ' ' + char.lower()
                        else:
                            aux += char
                else:
                    if i == 0:
                        aux += char.upper()
                    else:
                        aux += char
        return aux


class _FileListUpdater(FileSystemEventHandler):
    """Simple watchdog handler used for auto-updating the profiles list

    """
    def __init__(self, handler):
        self.handler = handler

    def on_created(self, event):
        super(_FileListUpdater, self).on_created(event)
        if isinstance(event, FileCreatedEvent):
            self.handler()

    def on_deleted(self, event):
        super(_FileListUpdater, self).on_deleted(event)
        if isinstance(event, FileDeletedEvent):
            self.handler()
github dagster-io / dagster / python_modules / dagit / dagit / cli.py View on Github external
create_app,
    RepositoryContainer,
)

from .pipeline_run_storage import (
    PipelineRunStorage,
    LogFilePipelineRun,
    InMemoryPipelineRun,
)


def create_dagit_cli():
    return ui


class ReloaderHandler(FileSystemEventHandler):
    def __init__(self, repository_container):
        super(ReloaderHandler, self).__init__()
        self.repository_container = repository_container

    def on_any_event(self, event):
        if event.src_path.endswith('.py'):
            print('Reloading repository...')
            self.repository_container.reload()


REPO_TARGET_WARNING = (
    'Can only use ONE of --repository-yaml/-y, --python-file/-f, --module-name/-m.'
)


@click.command(
github andreyfedoseev / django-static-precompiler / static_precompiler / watch.py View on Github external
import time

from typing import *  # noqa
from watchdog import events, observers

from . import exceptions, registry
from .compilers import BaseCompiler  # noqa


class EventHandler(events.FileSystemEventHandler):

    # noinspection PyShadowingNames
    def __init__(self, scanned_dir, verbosity, compilers):
        # type: (str, int, List[BaseCompiler]) -> None
        self.scanned_dir = scanned_dir
        self.verbosity = verbosity
        self.compilers = compilers
        super(EventHandler, self).__init__()

    def on_any_event(self, e):
        if e.is_directory or e.event_type not in ("created", "modified"):
            return
        path = e.src_path[len(self.scanned_dir):]
        if path.startswith("/"):
            path = path[1:]
        for compiler in self.compilers:
github gureckis / collecting_behavioral_data_online / build_site.py View on Github external
from jinja2 import Environment, FileSystemLoader
import os, sys
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import argparse

from config import *

env = Environment(loader=FileSystemLoader(TEMPLATES_FOLDER))
all_templates = os.listdir(TEMPLATES_FOLDER)


class MyHandler(FileSystemEventHandler):
	def on_modified(self, event):
		#self.write_template()
		file_changed = os.path.basename(event.src_path)
		if file_changed not in EXCLUDE_LIST:
			print file_changed + " changed"
			self.write_template(file_changed)
		else:
			# recuilt all files
			for fn in all_templates:
				if fn not in EXCLUDE_LIST: # don't need to rebuild excludes
					print fn + " changed"
					self.write_template(fn)

	# write parsed template to current folder
	def write_template(self, fn):
		template = env.get_template(fn)
github tevora-threat / Scout / scripts / alpr-unconstrained / license-plate-detection.py View on Github external
def run(self):
        event_handler = Handler()
        self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True)
        self.observer.start()
        try:
            while True:
                time.sleep(5)
        except:
            self.observer.stop()
            print("Error")

        self.observer.join()


class Handler(FileSystemEventHandler):

    @staticmethod
    def on_any_event(event):
        if event.is_directory:
            return None

        elif event.event_type == 'created':
            # Take any action here when a file is first created.
            print("Received created event - %s." % event.src_path)
            try:
                img_path = event.src_path
                print('\tScanning %s' % img_path)

                bname = basename(splitext(img_path)[0])

                R, _ = detect(vehicle_net, vehicle_meta, img_path, thresh=lp_threshold)
github soar-telescope / goodman_pipeline / pipeline / live / reduce.py View on Github external
import glob
import os
from watchdog.observers import Observer
from watchdog.events import (LoggingEventHandler,
                             FileSystemEventHandler,
                             FileModifiedEvent, FileCreatedEvent)
import time
import logging
from ccdproc import CCDData

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s - %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')


class EventHandler(FileSystemEventHandler):

    def __init__(self):
        self.log = logging.getLogger(__name__)

    def dispatch(self, event):
        print(dir(event))
        if isinstance(event, FileCreatedEvent):
            time.sleep(1)
            self.print_object(event)
        else:
            if event.is_directory:
                self.log.debug(event.__class__.__name__)
            else:
                self.log.info("File {:s}: {:s}".format(event.event_type,
                                                       os.path.basename(event.src_path)))
            #
github loomchild / reload / reload.py View on Github external
out = ''
        more = self.process != None
        while more:
            try:
                r = self.process.stdout.read()
                if not r:
                    more = False
                else:
                    out += r.decode("UTF-8")
            except IOError:
                more = False

        return out


class ReloadEventHandler(FileSystemEventHandler):

    def __init__(self, ignore_patterns=[]):
        self._modified = False
        self.ignore_patterns = [re.compile(r) for r in ignore_patterns]

    def dispatch(self, event):
        if event.is_directory:
            return

        path = os.path.basename(event.src_path)

        if any(r.match(path) for r in self.ignore_patterns):
            return

        super(ReloadEventHandler, self).dispatch(event)