How to monitor Python files for changes?



Monitoring files for changes in any language is hard because of cross platform issues. On python, there is a widely used cross platform library called watchdog that allows watching for changes. You can install it using:

$ pip install watchdog

Example

To watch a file called 'my_file.txt' using watchdog, you can use the simple program:

import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
    def on_modified(self, event):
        print("Got it!")
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path='.', recursive=False)
observer.start()
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()
observer.join()

 When you run this program and make any changes to any file in current directory, the on_modified function from MyHandler class gets called with the event. In the MyHandler class you can define your own functions to handle the events. In the path, you can specify the files/directories you want to monitor. To stop this program, use Ctrl + C


Advertisements