Monitor Directory with Random Event Handling using Watchdog

  • Share this:

Code introduction


The code defines a function `monitor_directory` that uses the watchdog library to monitor file events in a specified directory. It randomly selects the way to handle creation, modification, and deletion events. When a file event is detected, the `random_file_event_handler` function is called, which prints different information based on the event type.


Technology Stack : The code defines a function `monitor_directory` that uses the watchdog library to monitor file events in a specified directory. It randomly selects the way to handle creation, modification, and deletion events. When a file event is detected, the `random_file_event_handler` function is called, which prints different information based on the event type.

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
import random
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

def random_file_event_handler(path, event_type):
    # This function creates a custom event handler for watchdog that logs file events
    if event_type == 'created':
        print(f"File {path} has been created.")
    elif event_type == 'modified':
        print(f"File {path} has been modified.")
    elif event_type == 'deleted':
        print(f"File {path} has been deleted.")

def monitor_directory(path):
    event_handler = FileSystemEventHandler()
    event_handler.on_any_event = random_file_event_handler

    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while True:
            # Run indefinitely until stopped
            pass
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

# Code Information