如果在目录中创建了新文件,则启动python模块(看门狗)

时间:2019-02-26 13:05:10

标签: python observers watchdog python-watchdog

因此,当我在目录中创建文件然后使用新文件开始幻灯片播放时,我试图创建一个正在运行的python应用程序。我理解并设法正确地创建和执行了Watchdog-Observer,但现在我不知道如何继续。

在一个模块(mediachecker.py)中,将观察者写入,在main.py模块中,mediachecker.py文件被执行。现在,我想继续,仅在创建文件时(因此当观察者检测到on_created事件时)启动我的slideshow.py模块。

我认为我不太了解观察者或看门狗的概念,也不知道如何处理结果事件。

我希望你们能帮助我!

mediachecker.py

import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler 

path = '/Users/muser/Documents/directory'

class NewEventHandler(FileSystemEventHandler):
    def on_created(self, event):
        print('New files created')


class Checker(NewEventHandler):

    def watch(self):
        event_handler = NewEventHandler()
        observer = Observer()
        observer.schedule(event_handler, path, recursive=True)
        observer.start()
        try:
            while True:
                time.sleep(1) 
        except KeyboardInterrupt:
            observer.stop()
            observer.join()

main.py

from mediachecker import Checker

def main():
    checker = Checker()
    checker.watch()


if __name__ == "__main__":
    main()

slideshow.py当前为空,即将被写入

1 个答案:

答案 0 :(得分:0)

所以我找到了解决方案。我必须通过构造函数传递回调。

mediachecker.py

import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler 

path = '/Users/user/Documents/directory'

class NewEventHandler(FileSystemEventHandler):
    def __init__(self, callback):
        self.callback = callback
        super().__init__()

    def on_created(self, event):
        print('New files created')
        self.callback()

class Checker():
    def watch(self, callback):
        event_handler = NewEventHandler(callback)
        observer = Observer()
        observer.schedule(event_handler, path, recursive=True)
        observer.start()
        try:
            while True:
                time.sleep(1) 
        except KeyboardInterrupt:
            observer.stop()
            observer.join()

main.py

from mediachecker import Checker



def callback():
    print('callback')

def main():
    checker = Checker()
    checker.watch(callback)




if __name__ == "__main__":
    main()