views:

647

answers:

4

I'm trying to detect when a new file is created a directory or when an existing file is modified in a directory.

I tried searching for a script that would do this (preferably in python or bash) but came up short. My environment is linux with Python 2.6

Related Questions:
http://stackoverflow.com/questions/415856/how-to-detect-new-or-modified-files

+8  A: 

You can use gio which is the Filesystem part of GLib (In GLib's python bindings)

import gio

def directory_changed(monitor, file1, file2, evt_type):
   if (evt_type in (gio.FILE_MONITOR_EVENT_CREATED,
       gio.FILE_MONITOR_EVENT_DELETED)):
       print "Changed:", file1, file2, evt_type

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

however, your program must be running a GLib mainloop for the events to arrive. One quick way to test that is by using:

import glib
ml = glib.MainLoop()
ml.run()

GLib is a high-level library which is well suited for Applications. You don't have to care about which underlying system it uses for the file monitoring.


I now see you use Fedora Core 2. Really version 2? That might be too old to use GIO in GLib. Pyinotify that has been mentioned might be a better solution, although less portable.

kaizer.se
+1, Very interesting
Nadia Alramli
Too GNOME-ish! I don't like that, it's just an unnecessary dependency.
Andrey Vlasovskikh
Andrey: It is just GLib. Do you have it installed (if you're using Linux) or not?
kaizer.se
@kaizer.se I'm a Linux minimalist, I use `wmii` as a window manager and don't like various GNOME stuff. (But actually yes, I have `glib` installed because of `udev`, `avahi`, `mc`, ... ;)
Andrey Vlasovskikh
@Andrey: You may be right in that GLib is too big. It is a convenient interface, but to very many things.
kaizer.se
+4  A: 

If you're using Linux, you may try pyinotify that acts like an object-oriented wrapper around the inotify(7) system calls. The project website contains quite straightforward tutorials and examples.

Andrey Vlasovskikh
+1, Another interesting solution
Nadia Alramli
A: 

If you can use PyQt, there's QFileSystemWatcher that does just this.

Marcus Lindblom
A: 

There are also Python bindings for gamin.

Sebastian Noack