• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1.. include:: global.rst.inc
2
3.. _quickstart:
4
5Quickstart
6==========
7Below we present a simple example that monitors the current directory
8recursively (which means, it will traverse any sub-directories)
9to detect changes. Here is what we will do with the API:
10
111. Create an instance of the :class:`watchdog.observers.Observer` thread class.
12
132. Implement a subclass of :class:`watchdog.events.FileSystemEventHandler`.
14
153. Schedule monitoring a few paths with the observer instance
16   attaching the event handler.
17
184. Start the observer thread and wait for it generate events
19   without blocking our main thread.
20
21By default, an :class:`watchdog.observers.Observer` instance will not monitor
22sub-directories. By passing ``recursive=True`` in the call to
23:meth:`watchdog.observers.Observer.schedule` monitoring
24entire directory trees is ensured.
25
26
27A Simple Example
28----------------
29The following example program will monitor the current directory recursively for
30file system changes and simply print them to the console::
31
32    import time
33
34    from watchdog.events import FileSystemEvent, FileSystemEventHandler
35    from watchdog.observers import Observer
36
37
38    class MyEventHandler(FileSystemEventHandler):
39        def on_any_event(self, event: FileSystemEvent) -> None:
40            print(event)
41
42
43    event_handler = MyEventHandler()
44    observer = Observer()
45    observer.schedule(event_handler, ".", recursive=True)
46    observer.start()
47    try:
48        while True:
49            time.sleep(1)
50    finally:
51        observer.stop()
52        observer.join()
53
54To stop the program, press Control-C.
55