如何将参数传递给我的Python watchdog.events.PatternMatchingEventHandler

时间:2014-10-14 20:11:05

标签: python python-watchdog

我对Python很陌生,希望对大多数人来说,答案很明显。

我正在Python中创建一个代表ScanFolder的类。

在该课程的__init__中,我启动了一个watchdog.observers

只要在监视目录下更改文件,此观察者就会触发watchdog.events.PatternMatchingEventHandler。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import time

from watchdog.observers import Observer
import watchdog.events

path = sys.argv[1] if len(sys.argv) > 1 else '.'

class MyEventHandler(watchdog.events.PatternMatchingEventHandler):
    def on_any_event(self, event):
        print(event.src_path, event.event_type)

class ScanFolder:
    'Class defining a scan folder'

    def __init__(self, path):
        self.path = path
        self.documents = dict() # key = document label   value = Document reference

        self.event_handler = MyEventHandler(patterns=["*.jpg", "*.jpeg", "*.png", "*.bmp", "*.pdf"],
                                        ignore_patterns=[],
                                        ignore_directories=True)
        self.observer = Observer()
        self.observer.schedule(self.event_handler, self.path, recursive=False)
        self.observer.start()

    def stop(self):
        self.observer.stop()
        self.observer.join()

scan_folder = ScanFolder(path)

try:
    while True:
        time.sleep(1)
        """Here, I'll act on my scan_folder object that lists the discovered files"""
except KeyboardInterrupt:
    log.warning("Ouch !!! Keyboard interrupt received.")

scan_folder.stop()

我的问题如下:

如何通过scan_folder.event_handler()修改我的scan_folder对象?

实际上,我想在扫描文件夹中检测到文件的任何地方填充scan_folder.documents字典。

非常感谢,对不起我感到抱歉。

1 个答案:

答案 0 :(得分:2)

有很多方法可以做到这一点:但最简单的方法是将ScanFolder的绑定方法设置为on_any_event的{​​{1}}回调函数。所以你的代码变成了:

watchdog.events.PatternMatchingEventHandler

其他方式可以从watchdog.events.PatternMatchingEventHandler派生ScanFolder ....但是注入函数是python的力量之一