代码之家  ›  专栏  ›  技术社区  ›  Zu Jiry

看门狗作为后台线程-Python

  •  0
  • Zu Jiry  · 技术社区  · 6 年前

    我在main.py文件中有一个看门狗设置,它应该将Watcher作为守护进程运行(在后台),在运行时做一些事情(Watcher应该对此做出反应,例如创建一个测试文件),然后终止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()
    

    在执行操作时,我如何在后台运行Watcher,以及如何正确终止它?

    0 回复  |  直到 6 年前
        1
  •  1
  •   Muhammad Umar    6 年前

    这个解决方案对我很有效。Flask应用程序在主线程上,watcher在另一个线程上。

    flask application with watchdog observer

    推荐文章