[pygtk] GIO: Monitor directory for changes recursively

Jason Heeris jason.heeris at gmail.com
Wed Jun 16 08:18:54 WST 2010

Take the following demo code[1], which uses a GIO FileMonitor to
monitor a directory for changes:

   import gio

   def directory_changed(monitor, file1, file2, evt_type):
       print "Changed:", file1, file2, evt_type

   gfile = gio.File(".")
   monitor = gfile.monitor_directory(gio.FILE_MONITOR_NONE, None)
   monitor.connect("changed", directory_changed)

   import glib
   ml = glib.MainLoop()

After running this code, I can then create and modify child nodes and
be notified of the changes. However, this only works for immediate
children (I am aware that the docs don't say otherwise). The last of
the following shell commands will not result in a notification:

   touch one
   mkdir two
   touch two/three

Is there an easy way to make it recursive? I'd rather not manually
code something that looks for directory creation and adds a monitor,
removing them on deletion, etc (of course, if that's the only way,
then I've answered my own Q).

The intended use is for a VCS file browser extension, to be able to
cache the statuses of files in a working copy and update them
individually on changes. So there might by anywhere from tens to
thousands (or more) directories to monitor. I'd like to just find the
root of the working copy and add the file monitor there.

(By the way: the reason I'm avoiding pyinotify[1] is so that this
works under non-Linux kernels such as FreeBSD or... others. As far as
I'm aware, the GIO FileMonitor uses inotify underneath where
available, and I can understand not emphasising the implementation to
maintain some degree of abstraction, but it suggested to me that it
should be possible.)

— Jason

[1]  from StackOverflow, the GIO answer to "detect new or modified
files with python"
[2] http://trac.dbzteam.org/pyinotify

(If this hits the list twice, it's because it wasn't possible to
cancel my last attempt.)

More information about the pygtk mailing list