简体   繁体   English

如何仅将特定事件与 Python 看门狗匹配

[英]How to match only particular events with Python watchdog

I'm intending to use Python watchdog to handle a directory where files are written to, and I'm only interested in image files, trouble is I dont quite grok the code at this page .我打算使用 Python 看门狗来处理写入文件的目录,而我只对图像文件感兴趣,问题是我不太了解此页面上的代码。 This is my attempt:这是我的尝试:

from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler

class Beat(PatternMatchingEventHandler):
     def on_create(self,event):
             print event.src_path

if __name__ == "__main__":
    patt = ['\w+[.]jpeg']
    event_handler = Beat(patterns=patt,ignore_directories=True,) 
    observer = Observer()
    path = "./"
    observer.schedule(event_handler, path, recursive=True)
    observer.start()

I'm trying to use the pattern matching class, but I'm getting nothing.我正在尝试使用模式匹配类,但我什么也没得到。 How is it supposed to be used?它应该如何使用?

Based on the source code , fnmatch is being used under the hood.根据源代码fnmatch正在幕后使用。 fnmatch can only do UNIX glob-style pattern matching. fnmatch只能做 UNIX glob-style 模式匹配。 Which means you may have better luck with *.jpg than \\w+[.]jpeg这意味着*.jpg\\w+[.]jpeg有更好的运气

You can actually use the RegexMatchingEventHandler instead of PatternMatchingEventHandler to accomplish exactly what you want to do:您实际上可以使用 RegexMatchingEventHandler 而不是 PatternMatchingEventHandler 来完成您想要做的事情:

from watchdog.observers import Observer
from watchdog.events import RegexMatchingEventHandler  

class ExampleHandler(RegexMatchingEventHandler):
     def on_create(self, event):
             print(event.src_path)

if __name__ == "__main__":
    pattern = '\w+\.jpeg'
    event_handler = ExampleHandler(regexes=[pattern], ignore_directories=True) 
    observer = Observer()
    path = "./"
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    import time
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM