【问题标题】:How to close an HDF5 using low level Python API?如何使用低级 Python API 关闭 HDF5?
【发布时间】:2017-02-20 15:24:44
【问题描述】:

我能够通过结合以下堆栈溢出问题中定义的高级和低级 Python h5py API 来修改 HDF5 文件的缓存设置:How to set cache settings while using h5py high level interface?

当我尝试重命名文件时,我收到一条错误消息,提示 h5 文件仍处于打开状态。在 HDF5 写入操作完成并刷新文件后,带有 contextlib 的 Python“with”语句似乎没有关闭文件。如何确保使用低级或高级 API 关闭文件?你能举个例子吗?

import h5py
import contextlib
import os

filename = 'foo_2.h5'
propfaid = h5py.h5p.create(h5py.h5p.FILE_ACCESS)
settings = list(propfaid.get_cache())
settings[2] *= 5
propfaid.set_cache(*settings)

with h5py.File(filename, 'w') as hf:
    print 'file created'

with contextlib.closing(h5py.h5f.open(filename, fapl=propfaid)) as fid:

    f = h5py.File(fid)
    f.flush()

    # f.close() Seems to be working only in Python 3.4.3 but not in 2.7.7
    #and the "with contextlib.closing(...)  does not work on either version
    f.close()

os.rename(filename, 'foo_2.h5')

其他信息:
操作系统:Windows
Python:2.7.7
Anaconda 发行版:2.0.1
H5py版本:2.3.0

【问题讨论】:

  • 确切的错误信息是什么?
  • WindowsError: [错误 32] 该进程无法访问该文件,因为它正被另一个进程使用
  • 如果在代码中的其他位置打开文件(但未关闭),您可能会收到此错误。或者,如果某个其他进程(例如 virus checker or some other application 已打开文件。)您可以尝试使用 Unlocker or Process Explorer 查看哪些应用程序已打开文件。我在您发布的代码中没有看到任何错误。它本身不会引发错误(至少对于我在 linux 上不会)。
  • 我添加了一个用于测试的工作脚本。你的 linux 机器上运行的是哪个版本的 Python?
  • 谢谢。我已经打开了问题Unable to close an HDF5 using low level Python API

标签: python anaconda hdf5 h5py


【解决方案1】:

我认为您正在寻找 .close()

f.close()

虽然仔细观察,但我不确定为什么 contextlib.closing(...) 不起作用。

我将涉及 contextlib 的行编辑为:

with contextlib.closing(h5py.File(filename, fapl=propfaid)) as fid:

并删除

f = h5py.File(fid)

之后,我可以检查 fid 是否已关闭并且重命名文件是否按预期工作。

print fid
<Closed HDF5 file>

os.rename(filename, 'foo2.hdf5')

没有错误,目录检查显示新名称

【讨论】:

  • 我尝试使用 f.close() 但它不起作用。它会在 fid 中引发错误。
  • 它对用户 unutbu 有效,但我仍然遇到和你一样的问题。
  • @zd5151 我对您的代码进行了一些更改,这反映在我的回答中。该代码适用于我使用 python 2.7.11 和 h5py 2.5.0
猜你喜欢
  • 2011-12-27
  • 1970-01-01
  • 2019-06-30
  • 1970-01-01
  • 1970-01-01
  • 2011-10-14
  • 1970-01-01
  • 1970-01-01
  • 2012-12-29
相关资源
最近更新 更多