Search code examples
pythonpyinotify

how to make pyinotify to run a program on any modification over a file?


I have to watch for any input given to or any changes that made in the present content over a file, upon any modification i need to run a python program which is located in the same folder.

I tried my best to understand but i'm not able to get any good result. It would be of great help, if anyone can help me through this.

Thank you.. :)


Solution

  • import pyinotify,subprocess
    def onChange(ev):
        cmd = ['/bin/echo', 'File', ev.pathname, 'changed']
        subprocess.Popen(cmd).communicate()
    wm = pyinotify.WatchManager()
    wm.add_watch('file.watched', pyinotify.IN_MODIFY, onChange)
    notifier = pyinotify.Notifier(wm)
    notifier.loop()
    

    Replace cmd with the command you want to execute and file.watched with the file you want to watch, obviously.