看门狗忽略模式

Watchdog ignore pattern

我尝试与此处的其他帖子一起工作,但无法正常工作。我是 Python.

的新手

我需要 ignore_pattern 方面的帮助。

我正在将图片上传到一个文件夹,并且临时使用 __ 添加图片,因此上传文件时实际添加的图片是 __image-name.jpg。上传完成后,它会再次添加为 image-name.jpg(并删除 __image-name.jpg.

我想用看门狗忽略所有 __image-name.jpg 文件。

这是我的代码:

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

非常感谢。

event.src_path returns 是字符串吗?如果是这样,您可以使用字符串 class 的 startswith 方法来跳过不需要的图像。 例如:

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