Skip to content Skip to sidebar Skip to footer

How Do I Watch A File, Not A Directory For Changes Using Python?

The question: How do I watch a file for changes using Python? suggests using watchdog, but I found it was only able to watch a directory, not a file. watchdog-test.py is watchdog's

Solution 1:

You can watch a file with watchdog by watching the directory that the file is in and only responding to change events that effect your file. Something like this would do it for you:

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

classFileModifiedHandler(FileSystemEventHandler):

    def__init__(self, path, file_name, callback):
        self.file_name = file_name
        self.callback = callback

        # set observer to watch for changes in the directory
        self.observer = Observer()
        self.observer.schedule(self, path, recursive=False)
        self.observer.start()
        self.observer.join()

    defon_modified(self, event): 
        # only act on the change that we're looking forifnot event.is_directory and event.src_path.endswith(self.file_name):
            self.observer.stop() # stop watching
            self.callback() # call callbackfrom sys import argv, exit

if __name__ == '__main__':

    ifnotlen(argv) == 2:
        print("No file specified")
        exit(1)

    defcallback():
        print("FILE WAS MODIFED")

    FileModifiedHandler('.', argv[1], callback)

I was only able to test this on windows, but it should be os agnostic.

Post a Comment for "How Do I Watch A File, Not A Directory For Changes Using Python?"