python - 如何正确运行Watchdog的RegexMatchingEventHandler?

标签 python regex python-3.x watchdog python-watchdog

我正在为 GameApi 开发一个小工具。此 API 适用于 .log 文件。它们在特定位置提供。我想用看门狗观察这个位置,如果我使用 PatternMatchingEventHandler,它工作正常。但如果我使用 RegexMatchingEventHandler 它会失败。我想使用正则表达式,因为有很多 .log 文件,我只想检查今天的文件。

扩展:我使用 Watchdog 的功能:

on_created
on_deleted
on_moved
on_modified

该网站显示了我正在使用的代码: https://www.thepythoncorner.com/2019/01/how-to-create-a-watchdog-in-python-to-look-for-filesystem-changes/

我用 re 正常测试了我的正则表达式函数。这绝对是好事。但即使我尝试正则表达式条目:['\w+.log']它也不起作用。

我向您提供我的正则表达式以了解我想要做什么:

regexes = ["^Journal\.190901\d{6}\.\d{2}\.log$"]

每次更改一个 .log 文件时,我都希望收到一条消息,但这只有在我使用 PatternMatchingEventHAndle 时才会发生

编辑: 现在我向您展示我的最小示例:

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

if __name__ == "__main__":
    regexes = ["^Journal\.190901\d{6}\.\d{2}\.log$"]
    ignore_regexes= []
    ignore_directories = False
    case_sensitive = True
    my_event_handler = RegexMatchingEventHandler(regexes,ignore_regexes,ignore_directories,case_sensitive)

    def on_modified(event):
        print(f"hey buddy, {event.src_path} has been modified")

    my_event_handler.on_modified = on_modified

# Observer
    path = "."
    go_recursively = True
    my_observer = Observer()
    my_observer.schedule(my_event_handler, path, recursive=go_recursively)

    my_observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        my_observer.stop()
        my_observer.join()

最佳答案

这只是事件处理程序返回的路径模式,它以 path 中指定的文件夹根目录的路径开始 (path = "." 在您的示例中)。

  • 它可以帮助检查返回路径的任何模式,并检查您到底需要什么:

    regexes = ['.+']  # will match everything 
    
  • 要使用path = "."跟踪当前目录中的文件:

    # linux (example path : ./Journal[...].log)
    regexes = ['^\./Journal\.190901\d{6}\.\d{2}\.log$']
    
    # windows (example path : .\Journal[...].log)
    regexes = ["^\.\\\\Journal\.190901\d{6}\.\d{2}\.log$"]
    
    # both
    regexes = ["^\.(/|\\\\)Journal\.190901\d{6}\.\d{2}\.log$"]
    
  • 如果您定义了一个名为 logs 的子文件夹,并指定了根目录,如 path = "logs"

    # (example path : logs/Journal[...].log or logs\Journal[...].log
    regexes = ['^logs(/|\\\\)logs/Journal\.190901\d{6}\.\d{2}\.log$']
    

关于python - 如何正确运行Watchdog的RegexMatchingEventHandler?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57746487/

相关文章:

c - C 中的正则表达式(使用 regex.h)用于识别罗马数字

python - 重写 __eq__ 并比较两个对象

Python Pandas to_html 样式

java - 根据方括号中的值对字符串进行排序

python - 我如何将八个方向效果添加到我的 A 星算法而不是 4 个运动?

Java 正则表达式从字符串中拆分 double

python - 使用 PyObject_CallMethod 调用带有可选参数的函数

python - 将 pandas 数据框导出到 json 并返回到具有相同顺序列的数据框

python - 删除后 SQLAlchemy 仍然能够从 session 中获取对象

python - Arduino转串口+python转firebase UTF-8解码错误