Search code examples
pythonobserverswatchdogpython-watchdog

Start python module if new file in directory is created (watchdog)


So I am trying to create a python app which is getting active, when files are created in a directory and then startd a slideshow with the new files. I understood and managed to create and execute a Watchdog-Observer correctly but now I don't know how to continue.

In one module (mediachecker.py) the observer is written, in the module main.py the mediachecker.py ist getting executed. I now want to continue and only start my slideshow.py module when files are created (so when the observer detected an on_created event).

I think I didn't quite understand the concept of observers or watchdog and don't know how to handle the resulted events.

I hope you guys can help me out!

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 is currently empty and soon to be written


Solution

  • So I found a solution. I have to pass a callback through the constructors.

    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()