假设我有这样的代码
import time
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
class MyHandler(PatternMatchingEventHandler):
patterns = ["*/file.txt"]
def process(self, event):
"""
event.event_type
'modified' | 'created' | 'moved' | 'deleted'
event.is_directory
True | False
event.src_path
path/to/observed/file
"""
# the file will be processed there
print event.src_path, event.event_type # print now only for degug
if event.event_type == 'modified':
print fname
def on_modified(self, event):
self.process(event)
if __name__ == '__main__':
# args = sys.argv[1:]
fname = 'file.txt'
observer = Observer()
observer.schedule(MyHandler(), path='.')
observer.start()
try:
while True:
time.sleep(60)
except KeyboardInterrupt:
observer.stop()
observer.join()
我的目标是让用户patterns
在 MyHandler 类的变量中输入 fname。
import time
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
class MyHandler(PatternMatchingEventHandler):
patterns = ["*/"+fname]
def process(self, event):
"""
event.event_type
'modified' | 'created' | 'moved' | 'deleted'
event.is_directory
True | False
event.src_path
path/to/observed/file
"""
# the file will be processed there
print event.src_path, event.event_type # print now only for degug
if event.event_type == 'modified':
print fname
def on_modified(self, event):
self.process(event)
if __name__ == '__main__':
# args = sys.argv[1:]
fname = 'file.txt'
observer = Observer()
observer.schedule(MyHandler(), path='.')
observer.start()
try:
while True:
time.sleep(60)
except KeyboardInterrupt:
observer.stop()
observer.join()
我尝试了上面提到的一些方法,但没有奏效。它说fname is not defined
。好吧,我也试过patterns = [].append("*/"+fname)
了,也没有成功。
然后我尝试创建一个初始化函数
def __init__(fname):
self.patterns = [].append("*/"+fname)
并像过去一样observer.schedule(MyHandler(fname), path='.')
无赖!也没有成功。我怎样才能做到这一点?