Python watchdog

From wikinotes

Watchdog is a cross platform python module that monitors filesystem events (instead of repeatedly polling the hard-drive), and notifies python scripts. It is *THE* goto solution, and is builtin to several linux distros.

Documentation

https://pythonhosted.org/watchdog/index.html official docs

Usage

Each watchdog observer runs in it's own thread, you may want to reuse one observer for several matches.

Subclass a FileSystemEventHandler to define what you are looking for, and what to do when it is created/deleted/modified etc.

class NotifyOnPythonWrite(watchdog.events.PatternMatchingEventHandler):
    """
    subclass watchdog.events.FileSystemEventHandler
    """
    def __init__(self):
        super(NotifyOnPythonWrite, self).__init__(
            patterns = ['*.py', '*.pyc', '*.pyd']
        )
    def on_created(self, event):
        """ overridden method """
        # ignore if match is a directory
        if event.is_directory:
            return

        print(event.src_path)

Create Observer, and associate with FileSystemEventHandler.

observer = watchdog.observers.Observer()
observer.schedule(
    NotifyOnPythonWrite(), 
    '/home/willjp/progs', 
    recursive=True
)

Start/Stop monitoring filesystem events

# begin observing
observer.start()

# stop observering
observer.stop()
observer.join()