我使用此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()
它有效。现在,我的脚本不起作用。请帮忙。
答案 0 :(得分:0)
您没有调用父(PatternMatchingEventHandler
)对象构造函数
def __init__(self, logger, myfunction):
super().__init__() # <--- Put arguments to PatternMatchingEventHandler if constructor here if needed
self.logger = logger
self.myfunction = myfunction
需要调用构造函数来设置父类所需的一些实例变量,例如_ignore_directories
。