【问题标题】:How to run the RegexMatchingEventHandler of Watchdog correctly?如何正确运行Watchdog的RegexMatchingEventHandler?
【发布时间】:2019-09-01 13:42:45
【问题描述】:

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

扩展:我使用看门狗的功能:

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 正常测试了我的 Regex 函数。这绝对没问题。但即使我尝试了 Regex Entry: ['\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()

【问题讨论】:

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


    【解决方案1】:

    这只是事件处理程序返回的路径模式,它以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$']
      

    【讨论】:

    • 好的,我理解路径的事情。这段代码在windows系统上运行,我需要做一些特别的事情吗?为了获得正确的路径,我使用:from pathlib import Path
    • 嗯我在想这个,我在linux上试过,如果你使用['.+']返回的路径是什么?我不确定它如何处理 Windows 路径上的反斜杠。
    • 这也是我的想法。如何读取 ['.+'] 的输出。我应该用 import re 来做吗?
    • 我建议替换您当前的 regexes = ["^Journal\.190901\d{6}\.\d{2}\.log$"] 以检查 Windows 上返回的模式是什么
    • 很高兴它可以工作 ;) 正则表达式也可以像 Windows 一样奇怪,要写一个乱七八糟的反斜杠,你必须使用 4 (docs.python.org/3/library/re.html)
    猜你喜欢
    • 2022-12-03
    • 1970-01-01
    • 2020-08-12
    • 2012-05-22
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 2020-04-05
    • 2015-02-10
    相关资源
    最近更新 更多