我正在使用Python 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
类中的空数据框,以免出现错误吗?
答案 0 :(得分:0)
好像您从patterns
方法中丢失了__init__
参数,您还需要对父类的super()
方法进行__init__
调用({ {1}}),因此您可以向上传递pattern参数。
它应该看起来像这样:
PatternMatchingEventHandler
或者,对于更通用的情况,并支持class HandlerEQ54(PatternMatchingEventHandler):
def __init__(self, patterns=None):
super(HandlerEQ54, self).__init__(patterns=patterns)
...
event_handler = HandlerEQ54(patterns=["*.log"])
的所有参数:
PatternMatchingEventHandler