Random File Event Handler in Watchdog Monitoring

  • Share this:

Code introduction


This code defines a function named watch_directory that uses the watchdog library to monitor file change events in a specified directory. When a file is modified, created, or deleted, it will call the random_file_event_handler function to handle the event. This function randomly selects different handling methods, such as printing the file path and event type, or calling the custom random_file_event_handler function.


Technology Stack : The code uses the watchdog library and the following technologies: Python programming language, Observer pattern, FileSystemEventHandler, and lambda functions.

Code Type : The type of code

Code Difficulty :


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

def random_file_event_handler(path, event_type):
    if event_type == 'modified':
        print(f"File {path} has been modified.")
    elif event_type == 'created':
        print(f"File {path} has been created.")
    elif event_type == 'deleted':
        print(f"File {path} has been deleted.")

def watch_directory(directory_path):
    event_handler = FileSystemEventHandler()
    event_handler.on_any_event = random.choice([
        lambda path, event_type: random_file_event_handler(path, event_type),
        lambda path, event_type: print(f"Event {event_type} occurred in {path}"),
        lambda path, event_type: print(f"File {path} event detected: {event_type}")
    ])
    
    observer = Observer()
    observer.schedule(event_handler, directory_path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()