Directory Change Monitor with Callback

  • Share this:

Code introduction


This function monitors file changes in a specified directory and calls a specified callback function when changes occur.


Technology Stack : watchdog, Observer, FileSystemEventHandler

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
def monitor_directory_changes(path, callback):
    """
    Monitor directory changes and execute a callback function when changes occur.

    Args:
        path (str): The path of the directory to monitor.
        callback (function): The function to call when changes occur.
    """
    from watchdog.observers import Observer
    from watchdog.events import FileSystemEventHandler

    class ChangeHandler(FileSystemEventHandler):
        def on_any_event(self, event):
            callback(event)

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