Search code examples
python-3.xpython-watchdog

Watchdog as background thread - Python


I have this watchdog setup in file main.py which should run the the Watcher as a daemon (in the background), do some things while it is running (which the Watcher should react to, e.g. creating a test file) then terminate the Watcher.

from watchdog.events import PatternMatchingEventHandler
from watchdog.observers import Observer
import time
import threading


class Watcher:
    def watch_dir(self):
        patterns = "*"
        event_handler = PatternMatchingEventHandler(patterns)
        event_handler.on_any_event = self.on_any_event
        observer = Observer()
        observer.schedule(event_handler, 'someDirToObserve')
        observer.start()

        try:
            while True:
                time.sleep(2)
        except Exception as e:
            observer.stop()
            time.sleep(30)
        observer.join()

    def on_any_event(self, event):
        print(event)


def start_watcher(watcher):
    watcher.watch_dir()


def main():
    print("Start")
    watcher = Watcher()
    thread = threading.Thread(target=start_watcher(watcher), daemon=True)
    thread.start()
    test_file = 'SomeTestFile'
    test_file.unlink()
    with test_file.open('w') as f:
        f.write('Test')
    print("Oh shit")
    thread.join()


if __name__ == '__main__':
    main()

How can I run the Watcher in the Background while doing my operations and how do I terminate it correctly?


Solution

  • This solution worked for me. Flask app on main thread and watcher on another one.

    flask application with watchdog observer