使用看门狗检测文件创建 [英] Detect file creation with watchdog
问题描述
我试图检测何时在目录中创建了具有给定名称的文件.感谢看门狗,我正在这样做.正确检测到创建,但是检测完成后,我不知道如何正确终止应用程序.
I am trying to detect when a file with a given name is created in a directory. I am doing it thanks to watchdog. The creation is correctly detected but I don't know how to terminate the application properly once the detection is done.
我的代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import sys
import time
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
logging.basicConfig(level=logging.ERROR)
class MyEventHandler(FileSystemEventHandler):
def __init__(self, observer, filename):
self.observer = observer
self.filename = filename
def on_created(self, event):
print "e=", event
if not event.is_directory and event.src_path.endswith(self.filename):
print "file created"
self.observer.unschedule_all()
self.observer.stop()
def main(argv=None):
path = argv[1]
filename = argv[2]
observer = Observer()
event_handler = MyEventHandler(observer, filename)
observer.schedule(event_handler, path, recursive=False)
observer.start()
observer.join()
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
我是python的新手,我无法弄清楚出了什么问题.检测似乎是在专用线程中安排的,join()方法正在等待该线程终止.因此,我想我没有在观察者上调用正确的方法来停止等待/循环,但是看门狗文档似乎并不清楚指出可以使用的方法.
I am new to python and I cannot figure out what is wrong. The detection seems to be scheduled in a dedicated thread and the join() method is waiting for this thread to terminate. Thus, I suppose that I am not calling the right method on the observer to stop waiting/looping, but the watchdog documentation seems really not clear to point out what are the methods that may be used.
有人知道我如何实现目标吗?
Does someone have an idea how I can achieve my goal?
推荐答案
最后,看一下看门狗实现之后,不必在stop
之前调用unschedule_all
,这是自动完成的.删除包含此方法调用的行即可解决此问题,并且应用程序可以正常运行.
Finally, after taking a look at the watchdog implementation, it is not necessary to call unschedule_all
before stop
, this is done automatically. Removing the line containing this method call fixes the issue and the application is running perfectly.
这篇关于使用看门狗检测文件创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!