14

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.

2

7 Answers 7

31

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.

5
  • 1
    Thank you, thank you. This is great. Is there a similar lib for Windows (for compatibility reasons)?
    – Sam Dolan
    Jul 18, 2010 at 5:13
  • 1
    @sdolan, Windows has Directory Change Notifications. There are cross-platform solutions like pyqt's QFileSystemWatcher. Jul 18, 2010 at 5:28
  • 1
    @sdolan - also, PyGTK has the GIO file monitor.
    – detly
    Jul 18, 2010 at 7:28
  • @sdolan just to clarify, mhammond's win32 extensions for windows include the dir change notifications. there is a great example here: code.activestate.com/recipes/…
    – egbutter
    Nov 25, 2011 at 18:58
  • link is broken. Please fix it. Sep 15, 2014 at 23:09
9

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

With it, you can build what you want.

3

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

2

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.

2

Use FAM to put a monitor on the file.

1

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

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

0

Apparently, watchdog works on both Linux & OSX that can be used to monitor for changes in a directory as well with great example documentation. It also works with python3.x in case you don't want to be forced to use python2.x

Not the answer you're looking for? Browse other questions tagged or ask your own question.