Quickstart¶
Below we present a simple example that monitors the current directory recursively (which means, it will traverse any sub-directories) to detect changes. Here is what we will do with the API:
Create an instance of the
watchdog.observers.Observer
thread class.Implement a subclass of
watchdog.events.FileSystemEventHandler
.Schedule monitoring a few paths with the observer instance attaching the event handler.
Start the observer thread and wait for it generate events without blocking our main thread.
By default, an watchdog.observers.Observer
instance will not monitor
sub-directories. By passing recursive=True
in the call to
watchdog.observers.Observer.schedule()
monitoring
entire directory trees is ensured.
A Simple Example¶
The following example program will monitor the current directory recursively for file system changes and simply print them to the console:
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyEventHandler(FileSystemEventHandler):
def on_any_event(self, event):
print(event)
event_handler = MyEventHandler()
observer = Observer()
observer.schedule(event_handler, '.', recursive=True)
observer.start()
try:
while True:
time.sleep(1)
finally:
observer.stop()
observer.join()
To stop the program, press Control-C.