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.
My piece of code is the following:
#!/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))
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?