Monitoring Filesystem Events with RandomFileHandler

  • Share this:

Code introduction


This code defines a function named random_file_handler that uses the watchdog library to monitor filesystem events in a specified path and prints out the event type, path, size, and last modified time. The function accepts a path and a recursive monitoring flag as parameters.


Technology Stack : The code uses the watchdog library and its related classes and methods, such as Observer and FileSystemEventHandler, to implement filesystem event monitoring.

Code Type : The type of code

Code Difficulty : Advanced


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

def random_file_handler(path, recursive=False):
    class RandomFileHandler(FileSystemEventHandler):
        def on_any_event(self, event):
            if event.is_directory and not recursive:
                return
            print(f"Event type: {event.event_type}")
            print(f"Path: {event.src_path}")
            print(f"Size: {event.src_path.size() if hasattr(event.src_path, 'size') else 'N/A'}")
            print(f"Last modified: {time.ctime(event.src_path.stat().st_mtime)}")

    event_handler = RandomFileHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=recursive)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()