我有一个长时间运行的进程,它从给定的源检索数据,每秒使用HDFStore将更新的数据帧保存到同一个文件中。下面的代码是HDFWriter类,其write方法每秒都会调用一个数据帧和时间戳。
class HDFWriter(object):
def __init__(self, source):
self.source = source
self.date = None
self.hdf = self.create_hdfstore()
self.logger = logging.getLogger(source)
def create_hdfstore(self):
self.date = datetime.now()
manager = HDFFileManager(self.source, self.date)
return HDFStore(manager.get_partial_path(), complib = 'zlib', complevel = 9)
@staticmethod
def get_df_name(timestamp):
return '{:02d}/{}'.format(datetime.fromtimestamp(timestamp).hour, int(timestamp))
def check_rotation(self, timestamp):
current_date = datetime.fromtimestamp(timestamp)
if current_date.date() != self.date.date():
if self.hdf:
self.hdf.close()
self.hdf = self.create_hdfstore()
def write(self, data, timestamp):
self.check_rotation(timestamp)
table_name = self.get_df_name(timestamp)
try:
self.hdf.put(table_name, data, format = 'table', data_columns = True)
except Exception as e:
self.logger.error("Failed writing data")
数据框存储在XX / 123456790下,其中第一部分是一天中的小时,第二部分是时间戳。 HDFFileManager只管理是否已存在具有所需名称的文件并检索仍然可用的路径,因此可以忽略它的内部函数。
在资源有限的机器中,当文件增长接近该大小时,假设大约1GB,由于内存不足,进程将失败,从而触发致命的python异常。
HDFStore追加方法有任何已知问题吗?这似乎是内存泄漏。我试图隔离内存消耗问题,我发现如果我禁用HDFWriter(项目写入其他输出),问题就会消失。
有没有其他方法可以将Dataframes写入hdf文件?我研究过使用msgpack二进制格式来存储/加载来自hdf文件的数据帧,有什么建议吗?