0
我使用此http://brunorocha.org/python/watching-a-directory-for-file-changes-with-python.html示例來解決此任務。它的工作。 當我還沒有使用OOP。現在,我試圖重寫我的代碼,面向對象,我做了什麼: 我創建的文件名稱爲MyHandler.py使用Python觀察文件更改的目錄不起作用
#!/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()
而且它工作。現在,我的腳本不起作用。請幫忙。