pythonpython-3.xwatchdogpython-watchdog

Watchdog ignore pattern


I tried working with other posts on here about this, but couldn't get it to work. I'm a newbie with Python.

I need help with ignore_pattern.

I'm uploading images to a folder and temporarily images are being added with __, so the actual image added while file is uploading is __image-name.jpg. After it's done uploading it gets added again as image-name.jpg (and deletes the __image-name.jpg.

I want to ignore all the __image-name.jpg files with watchdog.

Here's my code:

class Watcher:
    DIRECTORY_TO_WATCH = "director/where/images/are/uploaded"

    def __init__(self):
        self.observer = Observer()

    def run(self):
        event_handler = Handler()
        self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True)
        self.observer.start()
        try:
            while True:
                time.sleep(5)
        except:
            self.observer.stop()
            print("Error")

        self.observer.join()


class Handler(FileSystemEventHandler):

    @staticmethod
    def on_any_event(event):
        if event.is_directory:
            return None

        elif event.event_type == 'created':
            # Take any action here when a file is first created.
            print(event.src_path)
            img = Image.open(event.src_path)
            for result in engine.classify_with_image(img, top_k=3):
              print('---------------------------')
              print(labels[result[0]])
              print('Score : ', result[1])

        # elif event.event_type == 'modified':
            # Taken any action here when a file is modified.
            # print("Received modified event - %s." % event.src_path)

        elif event.event_type == 'deleted':
            # Taken any action here when a file is deleted.
            print("Received deleted event - %s." % event.src_path)

if __name__ == '__main__':
    w = Watcher()
    w.run()

Thank you so much.


Solution

  • Does event.src_path returns a string? If so you can use the startswith method of the string class to skip over the images you don't want. For example:

    elif event.event_type == 'created':
                # Take any action here when a file is first created.
                print(event.src_path)
                
                # Check if this filename starts with "__" and execute the next block
                if not event.src_path.startswith('__'):
                  img = Image.open(event.src_path)
                  for result in engine.classify_with_image(img, top_k=3):
                    print('---------------------------')
                    print(labels[result[0]])
                    print('Score : ', result[1])
                # else do nothing