简体   繁体   English

关闭打开的h5py数据文件

[英]Close an open h5py data file

In our lab we store our data in hdf5 files trough the python package h5py . 在我们的实验室中,我们通过python包h5py将数据存储在hdf5文件中。

At the beginning of an experiment we create an hdf5 file and store array after array of array of data in the file (among other things). 在实验开始时,我们创建一个hdf5文件,并在文件中的数据数组之后存储数组(以及其他内容)。 When an experiment fails or is interrupted the file is not correctly closed. 当实验失败或被中断时,文件未正确关闭。 Because our experiments run from iPython the reference to the data object remains (somewhere) in memory. 因为我们的实验是从iPython运行的, iPython对数据对象的引用仍然(在某处)存储在内存中。

Is there a way to scan for all open h5py data objects and close them? 有没有办法扫描所有打开的h5py数据对象并关闭它们?

This is how it could be done (I could not figure out how to check for closed-ness of the file without exceptions, maybe you will find): 这是如何做到的(我无法弄清楚如何在没有例外的情况下检查文件的封闭性,也许你会发现):

import gc
for obj in gc.get_objects():   # Browse through ALL objects
    if isinstance(obj, h5py.File):   # Just HDF5 files
        try:
            obj.close()
        except:
            pass # Was already closed

Another idea: 另一个想法:

Dpending how you use the files, what about using the context manager and the with keyword like this? 在讨论如何使用文件时,使用上下文管理器和with关键字如何?

with h5py.File("some_path.h5") as f:
   f["data1"] = some_data

When the program flow exits the with-block, the file is closed regardless of what happens, including exceptions etc. 当程序流退出with-block时,无论发生什么情况,文件都会关闭,包括异常等。

pytables (which h5py uses) keeps track of all open files and provides an easy method to force-close all open hdf5 files. pytablesh5py使用)跟踪所有打开的文件,并提供一种强制关闭所有打开的hdf5文件的简单方法。

import tables
tables.file._open_files.close_all()

That attribute _open_files also has helpful methods to give you information and handlers for the open files. 该属性_open_files还提供了有用的方法来为您提供打开文件的信息和处理程序。

I've found that hFile. 我发现了hFile。 bool () returns True if open, and False otherwise. bool ()如果打开则返回True,否则返回False。 This might be the simplest way to check. 这可能是最简单的检查方法。 In other words, do this: 换句话说,这样做:

hFile = h5py.File(path_to_file)
if hFile.__bool__():
       hFile.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM