Directory Change Monitoring with Watchdog Library

  • Share this:

Code introduction


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


Technology Stack : watchdog

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def monitor_directory(path, callback):
    from watchdog.observers import Observer
    from watchdog.events import FileSystemEventHandler

    class MyHandler(FileSystemEventHandler):
        def on_modified(self, event):
            callback(event)

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