You can download this code by clicking the button below.
This code is now available for download.
This code defines a custom function based on the watchdog library to monitor file system events such as creation, modification, and deletion. The function randomly selects an event type and a file system path to watch, and defines a custom event handler class to handle these events.
Technology Stack : watchdog, Python
Code Type : The type of code
Code Difficulty :
import random
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
def random_watchdog_function():
# This function randomly selects features from the watchdog library to create a custom function
# Randomly select an event type
event_types = ["created", "modified", "deleted"]
event_type = random.choice(event_types)
# Randomly select a file system path to watch
path_to_watch = "/tmp/watchdog_example"
# Define a custom event handler based on the selected event type
class CustomEventHandler(FileSystemEventHandler):
def on_event(self, event):
if event.event_type == event_type:
if event_type == "created":
print(f"File {event.src_path} has been created.")
elif event_type == "modified":
print(f"File {event.src_path} has been modified.")
elif event_type == "deleted":
print(f"File {event.src_path} has been deleted.")
# Set up the observer and start watching the directory
event_handler = CustomEventHandler()
observer = Observer()
observer.schedule(event_handler, path_to_watch, recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()