Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I "watch" a file for modification / change? [duplicate]

Tags:

python

linux

I would like to invoke my chrome or firefox browser when a file that I specify is modified. How could I "watch" that file to do something when it gets modified?

Programmatically it seems the steps are.. basically set a never ending interval every second or so and cache the initial modification date, then compare the date every second, when it changes invoke X.

like image 399
meder omuraliev Avatar asked Jul 18 '10 04:07

meder omuraliev


2 Answers

As noted, you can use pyinotify:

E.g.:

import webbrowser
import pyinotify

class ModHandler(pyinotify.ProcessEvent):
    # evt has useful properties, including pathname
    def process_IN_CLOSE_WRITE(self, evt):
            webbrowser.open(URL)

handler = ModHandler()
wm = pyinotify.WatchManager()
notifier = pyinotify.Notifier(wm, handler)
wdd = wm.add_watch(FILE, pyinotify.IN_CLOSE_WRITE)
notifier.loop()

This is more efficient than polling. The kernel tells you when it does the operation, without you having to constantly ask.

like image 83
Matthew Flaschen Avatar answered Oct 12 '22 05:10

Matthew Flaschen


The Linux Kernel has a file monitoring API called inotify. A python binding is pyinotify.

With it, you can build what you want.

like image 44
Dr. Snoopy Avatar answered Oct 12 '22 05:10

Dr. Snoopy