我曾经为Python构建的解析器创建了一个守护进程。我需要观察一系列文件并用Python处理它们,它必须是一个真正的多操作系统解决方案(本例中是Windows&Linux)。我写了一个程序,通过检查文件的修改时间来监视文件列表。程序会休眠一段时间,然后检查正在监视的文件的修改时间。如果修改时间比之前注册的时间新,那么文件已经更改,因此必须对该文件进行处理。在
像这样:import os
import time
path = os.path.dirname(__file__)
print "Looking for files in", path, "..."
# get interesting files
files = [{"file" : f} for f in os.listdir(path) if os.path.isfile(f) and os.path.splitext(f)[1].lower() == ".src"]
for f in files:
f["output"] = os.path.splitext(f["file"])[0] + ".out"
f["modtime"] = os.path.getmtime(f["file"]) - 10
print " watching:", f["file"]
while True:
# sleep for a while
time.sleep(0.5)
# check if anything changed
for f in files:
# is mod time of file is newer than the one registered?
if os.path.getmtime(f["file"]) > f["modtime"]:
# store new time and...
f["modtime"] = os.path.getmtime(f["file"])
print f["file"], "has changed..."
# do your stuff here
它看起来不像是一流的代码,但它工作得很好。在
关于这个问题还有其他一些问题,但我不知道他们是否能直接回答你的问题:
希望这有帮助!在