3

I need to create FileCreatedEvents for files that exist in the directory when my watchdog app starts up. I've looked at a couple of things online to try and accomplish them, but none of them will work with my current approach:

Python Watchdog process existing files on startup https://www.reddit.com/r/learnpython/comments/fz57og/watchdog_how_to_include_existing_files/fn34dgk/

The first approach seems like it will work, but I'm not using a queue. I have pairs of files, and I can't act on those files until the pair is received. So I add files to a list as they come in and then check for the pair and if it exists I do stuff.

Here's my version of the approach:

class Watcher():

    observer = None
    directory = None
    pattern = None

def __init__(self, directory, pattern):
    
    self.observer = Observer()
    self.directory = directory
    self.pattern = pattern

def run(self):
    event_handler = Handler(self.pattern)
    self.observer.daemon=True
    self.observer.schedule(event_handler, path=self.directory, recursive=False)      
    
    self.observer.start() 
    log.info("Watcher started...")

    log.info("Checking for existing files...")
    for file in os.listdir(self.directory):
        filename = os.path.join(self.directory, file)
        if os.path.isfile(filename) and "hash" not in filename:
            event = FileCreatedEvent(filename)
            event.event_type = "created"
            print(event) 
#prints: <FileCreatedEvent: event_type=created, src_path='my_file.txt', is_directory=False>
            self.observer.event_queue.put((event, self.observer))
            

    try:
        while True:
            time.sleep(2)
    except KeyboardInterrupt:
        self.observer.stop()
        log.info("Watcher stopped")
    observer.join()

I've tried to implement this within my code, and everything is working up until this line:

self.observer.event_queue.put((event, self.observer))

I've also tried this:

event_handler.dispatch(event)

UPDATE:

It seems to create the event, but then I don't know how to actually trigger or fire the event. Thanks in advance for any help

For anyone looking for this, I had an unrelated block of code that was preventing one of the methods I tried from working. This is what ended up being the solution:

event_handler.on_created(event)

hyphen
  • 2,368
  • 5
  • 28
  • 59

0 Answers0