Created
July 26, 2017 18:12
-
-
Save caseyanderson/40c81d300fd3dbf0df5e539ddf34b0a2 to your computer and use it in GitHub Desktop.
watches a directory for file events and responds with handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
watcher and handler | |
to install watchdog for python3: pip3 install watchdog | |
sourced from https://www.michaelcho.me/article/using-pythons-watchdog-to-monitor-changes-to-a-directory | |
''' | |
import time | |
from watchdog.observers import Observer | |
from watchdog.events import FileSystemEventHandler | |
class Watcher: | |
DIRECTORY_TO_WATCH = "/path/to/test/" | |
def __init__(self): | |
self.observer = Observer() | |
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 ) | |
elif event.event_type == 'modified': | |
# Taken any action here when a file is modified. | |
print( "Received modified event - %s." % event.src_path ) | |
if __name__ == '__main__': | |
w = Watcher() | |
w.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment