If you want a general solution you should take pyinotify, which is a wrapper for the Linux kernel's inotify feature (kernel version >= 2.6.13). With it you can register for certain events in the filesystem, like e.g. in the following code:
from pyinotify import WatchManager, ThreadedNotifier, ProcessEvent, EventsCodes
file_to_monitor = "/tmp/test.py"
class FSEventHook(ProcessEvent):
def __init__(self, watch_path):
ProcessEvent.__init__(self)
wm = WatchManager()
wm.add_watch(watch_path, EventsCodes.ALL_FLAGS['IN_CLOSE_WRITE'], rec=False)
self.notifier = ThreadedNotifier(wm, self)
def start(self):
self.notifier.start()
def process_IN_CLOSE_WRITE(self, event):
if os.path.isfile(event.pathname):
print "%s changed"%pathname
fshook = FSEventHook(file_to_monitor)
fshook.start()
The following events are supported: IN_MOVED_FROM, IN_CREATE, IN_ONESHOT, IN_IGNORED, IN_ONLYDIR, IN_Q_OVERFLOW, IN_MOVED_TO, IN_DELETE, IN_DONT_FOLLOW, IN_CLOSE_WRITE, IN_MOVE_SELF, IN_ACCESS, IN_MODIFY, IN_MASK_ADD, IN_CLOSE_NOWRITE, IN_ISDIR, IN_UNMOUNT, IN_DELETE_SELF, ALL_EVENTS, IN_OPEN, IN_ATTRIB. For each of them you have to implement its own process_XXX() method, which will be called back if the event is triggered.