使用 Python 监视目录中的文件更改不起作用

Watching a directory for file changes with Python does not work

我使用这个 http://brunorocha.org/python/watching-a-directory-for-file-changes-with-python.html 示例来解决此任务。它奏效了。 当我还没有使用 OOP 时。现在,我正在尝试将我的代码重写为 OOP,我做了什么: 我创建了名称为 MyHandler.py

的文件
#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys

from watchdog.events import PatternMatchingEventHandler

class MyHandler(PatternMatchingEventHandler):
    patterns = ["*.xml", "*.lxml"]

    def __init__(self, logger, myfunction):
        self.logger = logger
        self.myfunction = myfunction

    def process(self, event):
        """
        event.event_type
            'modified' | 'created' | 'moved' | 'deleted'
        event.is_directory
            True | False
        event.src_path
            path/to/observed/file
        """
        self.logger.debug("target: {} was {}".format(event.src_path, event.event_type))
        self.myfunction()

    def on_created(self, event):
        self.process(event)

接下来,我在我的另一个文件中调用它,我在其中具有读取 xml:

的功能
observer = Observer()
observer.schedule(MyHandler(self.logger, self.read_xml), path=self.mydir)
observer.start()

try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()

observer.join()

而且,当我尝试调用它时,我有:

AttributeError: 'MyHandler' object has no attribute '_ignore_directories'

哪里出错了?在我使用 OOP 进行实验之前,我有:

class MyHandler(PatternMatchingEventHandler):
    patterns = ["*.xml*", "*.lxml"]

    def process(self, event):
        """
        event.event_type
            'modified' | 'created' | 'moved' | 'deleted'
        event.is_directory
            True | False
        event.src_path
            path/to/observed/file
        """
        logger.debug("Target: {} was {}".format(event.src_path, event.event_type))
        read_xml()

    def on_created(self, event):
        self.process(event)

    if __name__ == "__main__"

        observer = Observer()
        observer.schedule(MyHandler(), path=mydir)
        observer.start()

        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            observer.stop()

        observer.join()

它奏效了。现在,我的脚本不起作用。请帮忙。

您没有调用父 (PatternMatchingEventHandler) 对象构造函数

def __init__(self, logger, myfunction):
    super().__init__() # <--- Put arguments to PatternMatchingEventHandler if constructor here if needed
    self.logger = logger
    self.myfunction = myfunction

需要调用构造函数来设置父class所需的一些实例变量,例如_ignore_directories