Code introduction
The code defines a function named `monitor_directory` that monitors file changes in a specified directory and calls the `callback` function when a file is modified. It uses the `Observer` and `FileSystemEventHandler` classes from the watchdog library.
Technology Stack : The code defines a function named `monitor_directory` that monitors file changes in a specified directory and calls the `callback` function when a file is modified. It uses the `Observer` and `FileSystemEventHandler` classes from the watchdog library.
Code Type : The type of code
Code Difficulty : Intermediate
def monitor_directory(directory, 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, directory, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()