Watchdog ignore pattern

烈酒焚心 提交于 2020-07-10 10:26:26

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/62801303/watchdog-ignore-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!