我正在尝试学习python-watchdog,但我有点困惑为什么我设置的工作运行不止一次。所以,这是我的设置:
#handler.py
import os
from watchdog.events import FileSystemEventHandler
from actions import run_something
def getext(filename):
return os.path.splitext(filename)[-1].lower()
class ChangeHandler(FileSystemEventHandler):
def on_any_event(self, event):
if event.is_directory:
return
if getext(event.src_path) == '.done':
run_something()
else:
print "event not directory.. exiting..."
pass
观察者的设置如下:
#observer.py
import os
import time
from watchdog.observers import Observer
from handler import ChangeHandler
BASEDIR = "/path/to/some/directory/bin"
def main():
while 1:
event_handler = ChangeHandler()
observer = Observer()
observer.schedule(event_handler, BASEDIR, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
if __name__ == '__main__':
main()
最后,这样的行为:
#actions.py
import os
import subprocess
def run_something():
output = subprocess.check_output(['./run.sh'])
print output
return None
.. ./run.sh
只是一个shell脚本我希望在.done
/path/to/some/directory/bin
的文件时运行
#run.sh
#!/bin/bash
echo "Job Start: $(date)"
rm -rf /path/to/some/directory/bin/job.done # remove the .done file
echo "Job Done: $(date)"
但是,当我发出python observer.py
然后在touch job.done
上执行/path/to/some/directory/bin
时,我发现我的shell脚本./run.sh
运行了三次而不是一次.. < / p>
我很困惑为什么这会运行三次而不只是一次(我确实删除了我的bash脚本上的job.done
文件)
答案 0 :(得分:3)
要调试监视程序脚本,打印看门狗所看到的事件非常有用。一个文件编辑或CLI命令(例如touch
)可能导致多个监视程序事件。例如,如果插入print语句:
class ChangeHandler(FileSystemEventHandler):
def on_any_event(self, event):
print(event)
记录每个事件,运行
% touch job.done
产生
2014-12-24 13:11:02 - <FileCreatedEvent: src_path='/home/unutbu/tmp/job.done'>
2014-12-24 13:11:02 - <DirModifiedEvent: src_path='/home/unutbu/tmp'>
2014-12-24 13:11:02 - <FileModifiedEvent: src_path='/home/unutbu/tmp/job.done'>
上面有两个src_path
以job.done
结尾的事件。因此,
if getext(event.src_path) == '.done':
run_something()
运行两次,因为有FileCreatedEvent
和FileModifiedEvent
。
您可能最好只监控FileModifiedEvent
s。