- 1 year ago
Watchdog in Python to look for filesystem changes (Windows 10)
To create a watchdog in Python that monitors filesystem changes on Windows 10, you can use the watchdog
library. Here's an example that demonstrates how to set up a basic watchdog to monitor file and directory changes:
pythonfrom watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyFileSystemEventHandler(FileSystemEventHandler):
def on_any_event(self, event):
print(f"Event: {event.event_type} - Path: {event.src_path}")
if __name__ == "__main__":
path = "C:/path/to/directory" # Specify the directory you want to monitor
event_handler = MyFileSystemEventHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
pass
except KeyboardInterrupt:
observer.stop()
observer.join()
In the example above, we import the necessary classes from the watchdog
library: Observer
and FileSystemEventHandler
. We create a custom event handler class, MyFileSystemEventHandler
, which inherits from FileSystemEventHandler
and overrides the on_any_event
method to print information about the event.
In the if __name__ == "__main__":
block, we specify the path to the directory you want to monitor by assigning it to the path
variable.
We create an instance of MyFileSystemEventHandler
and an Observer
object. We then use the observer's schedule
method to set up the event handler to watch the specified path, with recursive=True
indicating that subdirectories should also be monitored.
The observer is started, and the program enters an infinite loop, waiting for events to occur. To exit the program, you can use Ctrl+C, which raises a KeyboardInterrupt
exception. In the exception block, we stop the observer and wait for it to join.
When any filesystem change occurs in the monitored directory (such as file creations, modifications, or deletions), the on_any_event
method of MyFileSystemEventHandler
will be called, and information about the event will be printed.
Note that you'll need to install the watchdog
library if you haven't already. You can do this using pip
by running pip install watchdog
in your command prompt or terminal.
Feel free to customize the on_any_event
method in MyFileSystemEventHandler
to perform specific actions based on the type of filesystem events you are interested in.