Newbie-Question: Oberserving an directory
Cliff Wells
logiplexsoftware at earthlink.net
Fri Jun 21 13:23:47 EDT 2002
On Fri, 21 Jun 2002 18:21:59 +0200
Marcus Klein wrote:
> Hi there,
>
> I want to observe an directory to check if a new file has been put in, if
> that happens I want to start an event.
>
> Does anyone have a good idea how to start, I've tried it with signal, but
> either I am too stupid or it is the complete wrong way :-/
AFAIK, you'll have to poll the directory contents. This solution may be
overkill for your needs, but hey.
import os, time
import threading, Queue
class DirScanner:
def __init__(self, directory, interval = 2):
self.dir = directory
self.queue = Queue.Queue()
self.running = 1
self.interval = interval
self.thread = threading.Thread(target = self._scan)
self.thread.start()
def _scan(self):
lastDir = os.listdir(self.dir)
while self.running:
thisDir = os.listdir(self.dir)
for f in thisDir:
try:
lastDir.index(f)
except ValueError: # new entry
self.queue.put(f)
lastDir = thisDir
time.sleep(self.interval)
def get(self, block = 1):
try:
return self.queue.get(block)
except Queue.Empty:
return None
def kill(self):
self.running = 0
if __name__ == '__main__':
ds = DirScanner("/tmp")
while 1:
f = ds.get(0)
if f is not None:
print f
ds.kill() # stop the thread
break
This will allow the main thread of execution to continue and you can check the
queue for new files when needed. Alternatively, you can call ds.get() without
the 0 argument and it will wait until a new filename is put on the Queue.
Good luck,
--
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308 (800) 735-0555 x308
More information about the Python-list
mailing list