python - 使用 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()
解决方案
推荐阅读
- typescript - 如何将 TypeScript 用于 next.js 服务器?
- java - 为什么这个方法总是返回 -1
- python - 与多处理一起使用时,PyTesseract 调用工作非常缓慢
- python - Pandas DataFrame 中列表中元素的位置
- javascript - 如何在数据更改时呈现动态数组并更新
- javascript - 将两个数字与字符串相加
- java - bonigarcia webdrivermanager firefox浏览器问题
- ruby - 为什么有这么多断言?简单的“断言”还不够吗?
- javascript - 通过 ES6 中的 Express 和使用 OOP 概念(类等)构建 Node js 项目
- php - Foreach 的 Selenium WebDrive 问题