monitoring folder in python

R

Raghul

Is it possible to monitor a folder in the python?My question is if I
put any file in it that particular folder my script should monitor the
folder and read the file name.If so what function can I use?

Thanx in advance
 
?

=?ISO-8859-1?Q?Andr=E9_S=F8reng?=

Raghul said:
Is it possible to monitor a folder in the python?My question is if I
put any file in it that particular folder my script should monitor the
folder and read the file name.If so what function can I use?

Thanx in advance

If you do not want to poll (check for changes yourself regularly),
here are some pointers:

In Windows:

With the win32 extensions, it's quite simple:

http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_changes.html

In Linux:

http://www.edoceo.com/creo/inotify/

http://www.student.lu.se/~nbi98oli/dnotify.html

http://www.lambda-computing.com/projects/dnotify/

Don't know of any Python extensions for the above, so you might
have to write your own if you want to use them from Python. Also,
you probably need to reconfigure and compile a new kernel. Have
tested inotify myself and it seems to work, you also get the filename
with the event. Only problem is it don't support monitoring a directory
recursive (subdirectories) like in Windows with ReadDirectoryChangesW.
 
D

Davide Salomoni

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,678
Members
48,796
Latest member
Greg L.

Latest Threads

Top