首页 > 解决方案 > 使用 dask 的 from_array 函数关闭文件

问题描述

我碰巧使用了 Dask 的“from_array”方法。正如在https://docs.dask.org/en/latest/array-creation.html的文档中一样,我执行以下操作:

>>> import h5py
>>> f = h5py.File('myfile.hdf5') # HDF5 file
>>> d = f['/data/path']          # Pointer on on-disk array
>>> x = da.from_array(d, chunks=(1000, 1000))

但是在这个例子中,你同意我在处理完数据后关闭 hdf5 文件吗?

如果是,则向 Dask 数组添加一个功能以允许仅传递文件指针和数据集键以便在 Dask 数组中包含一个例程可能会很有用,该例程将在 dask 数组对象时关闭源文件(如果有)被摧毁。

我知道一个好的方法是这样的:

>>> import h5py
>>> with h5py.File('myfile.hdf5') as f: # HDF5 file
>>>     d = f['/data/path']          # Pointer on on-disk array
>>>     x = da.from_array(d, chunks=(1000, 1000))

但有时它并不是很方便。例如,在我的代码中,我有一个函数,它从文件路径返回一个 dask 数组,中间有一些健​​全性检查,有点像:

>>> import h5py
>>> function get_dask_array(filepath, key)
>>>     f = h5py.File(filepath) # HDF5 file
>>>     # ... some sanity checks here
>>>     d = f[key] # Pointer on on-disk array
>>>     # ... some sanity checks here
>>>     return da.from_array(d, chunks=(1000, 1000))

在这种情况下,我发现返回文件指针并在处理期间将其放在一边,然后再关闭它是很难看的。

关于我应该怎么做的任何建议?

预先感谢您的回答,

问候,

编辑:现在我在包中使用全局变量,如下所示:

@atexit.register
def clean_files():
    for f in SOURCE_FILES:
        if os.path.isfile(s):
            f.close()

标签: pythondask

解决方案


推荐阅读