使用while循环监控文件夹并在条件满足时运行脚本
我正在尝试写一个脚本,用来监控一个文件夹。如果这个文件夹里有新文件被添加进来,就处理这个文件,然后把它移动到一个叫“DONE”的文件夹里。
我想我需要用一个循环来实现这个功能…我会用类似下面的方式来监控这个文件夹:
count = len(os.listdir('/home/lou/Documents/script/txts/'))
while (count = 1):
print Waiting...
我希望这个脚本每30秒检查一次文件夹里的文件数量。如果文件数量从1变成2,就运行处理文件的脚本;如果没有变化,就再等30秒再检查一次。处理完新文件后,文件数量会变回1。这个脚本会一直运行,24小时不停。
任何帮助都非常感谢。
谢谢。
lou
3 个回答
0
这里有一个通用的解决方案,当你调用它时,它会一直等待,直到你传入的目录被修改。这段代码可以在你对目录进行其他操作之前调用,比如计算里面有多少个文件等等。它可以用来阻止程序继续执行,直到目录被修改:
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)
注意,你可以覆盖默认的超时时间,默认是30秒。下面是这个函数的使用示例:
>>> att_dir = '/data/webalert/attachments'
>>> directory_modified(att_dir, 5) # Some time goes by while I modify the dir manually
True
这个函数在最多运行5秒后会返回true,前提是我在修改目录后立刻开始了等待。希望这对需要通用方法的人有所帮助。
2
要等待30秒,可以使用下面的代码:
import time # outside the loop
time.sleep(30)
6
根据文件夹的大小,如果文件夹的修改时间没有变化,最好只检查文件的数量。如果你在使用Linux系统,你可能还会对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)