D3l_Gato
D3l_Gato

Reputation: 1329

While loop to monitor folder and run script if conditon is true

I am trying to write a script that monitors a folder, and if the folder has a file added to it, process the file then move it to a DONE folder.

I think I want to use a while loop for this... I will monitor the folder with something like:

count = len(os.listdir('/home/lou/Documents/script/txts/'))
while (count = 1):
    print Waiting...

I want the script to check the len() every 30 seconds and if it changes from 1 to 2, run the script, otherwise wait onther 30 seconds and check the len(). The script will move the new file to a folder and the len() will return to 1. The script will run 24/7.

any help is greatly appreciated

thanks

lou

Upvotes: 4

Views: 4262

Answers (3)

radtek
radtek

Reputation: 36300

Here is a generic solution that when called, will wait FOREVER until the directory passed has been modified. This function can be called prior to any code that would do things with the directory such as count how many files etc.. It can be used to block execution until dir is modified:

def directory_modified(dir_path, poll_timeout=30):
    import os
    import time
    init_mtime = os.stat(dir_path).st_mtime
    while True:
        now_mtime = os.stat(dir_path).st_mtime
        if init_mtime != now_mtime:
            return True
        time.sleep(poll_timeout)

Notice you can overwrite the timeout, default being 30 seconds. Here is the function in use:

>>> att_dir = '/data/webalert/attachments'
>>> directory_modified(att_dir, 5)   # Some time goes by while I modify the dir manually
True

The function returns true after a max of 5 seconds run-time in case the sleep started as soon as I modified the directory. Hope this helps those in need of a generic approach.

Upvotes: 0

jordanm
jordanm

Reputation: 34964

Depending on the size of the directory, it may be best to only check the number of file if the mtime of the directory has changed. If you are using Linux, you may also be interested in inotify.

import sys
import time
import os

watchdir = '/home/lou/Documents/script/txts/'
contents = os.listdir(watchdir)
count = len(watchdir)
dirmtime = os.stat(watchdir).st_mtime

while True:
    newmtime = os.stat(watchdir).st_mtime
    if newmtime != dirmtime:
        dirmtime = newmtime
        newcontents = os.listdir(watchdir)
        added = set(newcontents).difference(contents)
        if added:
            print "Files added: %s" %(" ".join(added))
        removed = set(contents).difference(newcontents)
        if removed:
            print "Files removed: %s" %(" ".join(removed))

        contents = newcontents
    time.sleep(30)

Upvotes: 6

setrofim
setrofim

Reputation: 725

To wait 30 seconds do

import time # outside the loop

time.sleep(30)

Upvotes: 2

Related Questions