【问题标题】:How to initialize python watchdog pattern matching event handler如何初始化python看门狗模式匹配事件处理程序
【发布时间】:2019-06-06 10:05:54
【问题描述】:

我正在使用 Python Watchdog 来监视目录中是否有正在创建的新文件。在所述目录中创建了几种不同类型的文件,但我只需要监视一个文件类型,因此我使用 Watchdog PatternMatchingEventHandler,在其中我使用 patterns 关键字指定要监视的模式。

为了在后台正确执行代码(此处未显示),我需要在我的事件处理程序中初始化一个空数据框,但我无法让它工作。如果我在下面的代码中删除 __init__,那么一切都会正常工作。

我使用this answer 中的代码作为我自己的灵感。

我设置的代码如下:

from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
import time
import pandas as pd
import numpy as np
from multiprocessing import Pool

class HandlerEQ54(PatternMatchingEventHandler):

    def __init__(self):
        #Initializing an empty dataframe for storage purposes.
        data_54 = pd.DataFrame(columns = ['Barcode','DUT','Step12','Step11','Np1','Np2','TimestampEQ54'])
        #Converting to INT for later purposes
        data_54[['Barcode','DUT']]=data_54[['Barcode','DUT']].astype(np.int64)
        self.data = data_54

    def on_created(self,event):
        if event.is_directory:
            return True

        elif event.event_type == 'created':
        #Take action here when a file is created.
            print('Found new files:')
            print(event.src_path)
            time.sleep(0.1)

            #Creating process pool to return data
            pool1 = Pool(processes=4)
            #Pass file to parsing function and return parsed result.
            result_54 = pool1.starmap(parse_eq54,[(event.src_path,self.data)])
            #returns the dataframe rather than the list of dataframes returned by starmap
            self.data = result_54[0]


            print('Data read: ')
            print(self.data)


def monitorEquipment(equipment):
    '''Uses the Watchdog package to monitor the data directory for new files.
    See the HandlerEQ54 and HandlerEQ51 classes in multiprocessing_handlers for actual monitoring code.  Monitors each equipment.'''

    print('equipment')

    if equipment.upper() == 'EQ54':

        event_handler = HandlerEQ54(patterns=["*.log"])
        filepath = '/path/to/first/file/source/'

    # set up observer
    observer = Observer()
    observer.schedule(event_handler, path=filepath, recursive=True)
    observer.daemon=True
    observer.start()
    print('Observer started')
    # monitor
    try:
        while True:
            time.sleep(5)
    except KeyboardInterrupt:
        observer.unschedule_all()
        observer.stop()
    observer.join()

但是,当我执行 monitorEquipment 时,我收到以下错误消息:

TypeError: __init__() got an unexpected keyword argument 'patterns'

很明显,当我初始化我的处理程序类时我做错了,但我对它是什么(这可能反映了我对类的不太理想的理解)持空白。有人可以建议我如何正确初始化我的 HandlerEQ54 类中的空数据框,以免出现我的错误吗?

【问题讨论】:

    标签: python-3.x class python-watchdog


    【解决方案1】:

    看起来您缺少__init__ 方法中的patterns 参数,您还需要对父类(PatternMatchingEventHandler) 的__init__ 方法的super() 调用,因此您可以通过模式参数向上。

    它应该看起来像这样:

    class HandlerEQ54(PatternMatchingEventHandler):
    
        def __init__(self, patterns=None):
            super(HandlerEQ54, self).__init__(patterns=patterns)
    ...
    
    event_handler = HandlerEQ54(patterns=["*.log"])
    

    或者,对于更通用的情况并支持 PatternMatchingEventHandler 的所有参数:

    class HandlerEQ54(PatternMatchingEventHandler):
    
        def __init__(self, *args, **kwargs):
            super(HandlerEQ54, self).__init__(*args, **kwargs)
    ...
    
    event_handler = HandlerEQ54(patterns=["*.log"])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-25
      • 2023-03-03
      相关资源
      最近更新 更多