For now, loop to monitor the folder and run the script if conditon is true

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

I think I want to use the while loop for this ... I will control 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 len () every 30 seconds, and if it changes from 1 to 2, run the script, otherwise wait 30 seconds and check len (). the script will move the new file to the folder, and len () will return to 1. the script will run 24/7.

any help is appreciated

thanks

Lou

+4
source share
3 answers

Depending on the size of the directory, it is best to check the number of files if the time mtime in the directory has changed. If you use 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) 
+6
source

Wait 30 seconds

 import time # outside the loop time.sleep(30) 
+2
source

Here is a general solution that, when called, will wait FOREVER until the directory is changed. This function can be called before any code that will do something in the directory, for example, count the number of files, etc. It can be used to block execution until the dir changes:

 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) 

Please note that you can overwrite the timeout, the default is 30 seconds. Here is the function used:

 >>> 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 maximum runtime of 5 seconds in case of sleep start, as soon as I changed the directory. Hope this helps those who need a common approach.

0
source

Source: https://habr.com/ru/post/1384520/


All Articles