tags:

views:

195

answers:

7

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.

+1  A: 

The other option is to use a checksum. You can use a pattern similar to nose's nosy.py. I use the one from dingus to check my directory for modifications and run the test suite.

sdolan
+1  A: 

use a quick hash function, a cron job, and off you go!

Also, this looks relevant: http://en.wikipedia.org/wiki/Inotify

Gary
+4  A: 

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

With it, you can build what you want.

Matias Valdenegro
+2  A: 

Use FAM to put a monitor on the file.

Ignacio Vazquez-Abrams
+7  A: 

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.

Matthew Flaschen
Thank you, thank you. This is great. Is there a similar lib for Windows (for compatibility reasons)?
sdolan
@sdolan, Windows has [Directory Change Notifications](http://msdn.microsoft.com/en-us/library/aa365261%28VS.85%29.aspx). There are cross-platform solutions like pyqt's [QFileSystemWatcher](http://www.riverbankcomputing.com/static/Docs/PyQt4/html/qfilesystemwatcher.html).
Matthew Flaschen
@sdolan - also, PyGTK has the GIO file monitor.
detly
@Matthew and @detly: Thanks for the info.
sdolan
+1  A: 

Install inotify-tools and write a simple shell script to watch a file.

nwmcsween
A: 

Follow this tutorial on using inotify Inotify Example: Introduction to Inotify with a C Program Example

thegeek