monitoring folder in python
Davide Salomoni
dsalomoni at gmail.com
Tue Apr 5 06:34:41 EDT 2005
A straw-man solution in Python that monitors a directory for changes
(Linux only):
#!/usr/bin/env python2
import sys
import os
if sys.platform not in ("linux2",):
sys.exit("%s only runs on Linux" % os.path.basename(sys.argv[0]))
# TODO: we should check that kernel version >= 2.4.19
# e.g. with 'uname -r'
import fcntl
import signal
TESTDIRECTORY = "."
def notify(directory, handler):
fd = os.open(directory, os.O_RDONLY)
fcntl.fcntl(fd, fcntl.F_NOTIFY,
fcntl.DN_ACCESS|fcntl.DN_MODIFY|fcntl.DN_CREATE)
signal.signal(signal.SIGIO, handler)
def handler(signum, frame):
print "Something happened; signal =", signum
if __name__ == "__main__":
notify(TESTDIRECTORY, handler)
try:
signal.pause() # sleep until signal received
except KeyboardInterrupt:
pass
With Python 2.4 one could bind e.g. to signal.SIGRTMIN instead of the
default SIGIO and get additional info, as suggested by the C example in
Documentation/dnotify.txt (look in the Linux src tree). But then I am
note sure you can access a siginfo structure directly from Python. With
the example above, one would probably write the handler so that it
rescans the directory when called to detect what actually changed.
Davide
More information about the Python-list
mailing list