Directory Monitoring with Watchdog Library

  • Share this:

Code introduction


This function uses the watchdog library to monitor a specified directory. When a file in the directory is modified, it will call the callback function passed in.


Technology Stack : watchdog, Observer, FileSystemEventHandler

Code Type : The type of code

Code Difficulty : Advanced


                
                    
def monitor_directory(directory, on_modified):
    """
    Monitor a directory for changes and call a function when a file is modified.

    :param directory: The directory to monitor.
    :param on_modified: The function to call when a file is modified.
    """
    from watchdog.observers import Observer
    from watchdog.events import FileSystemEventHandler

    class ModifiedHandler(FileSystemEventHandler):
        def on_modified(self, event):
            if not event.is_directory:
                on_modified(event.src_path)

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