1
2import time
3from watchdog.observers import Observer
4from watchdog.events import FileSystemEventHandler
5
6
7class Watcher:
8 DIRECTORY_TO_WATCH = "/path/to/my/directory"
9
10 def __init__(self):
11 self.observer = Observer()
12
13 def run(self):
14 event_handler = Handler()
15 self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True)
16 self.observer.start()
17 try:
18 while True:
19 time.sleep(5)
20 except:
21 self.observer.stop()
22 print "Error"
23
24 self.observer.join()
25
26
27class Handler(FileSystemEventHandler):
28
29 @staticmethod
30 def on_any_event(event):
31 if event.is_directory:
32 return None
33
34 elif event.event_type == 'created':
35 # Take any action here when a file is first created.
36 print "Received created event - %s." % event.src_path
37
38 elif event.event_type == 'modified':
39 # Taken any action here when a file is modified.
40 print "Received modified event - %s." % event.src_path
41
42
43if __name__ == '__main__':
44 w = Watcher()
45 w.run()
46
47