python – 使用h5py打开已写入模式的hdf5文件

我同时运行相同的
Python程序作为不同的进程,这些都希望使用h5py Python包写入相同的hdf5文件.但是,只有一个进程可以在写入模式下打开给定的hdf5文件,否则您将收到错误

OSError: Unable to open file (unable to lock file, errno = 11, error
message = ‘Resource temporarily unavailable’)

During handling of the above exception, another exception occurred:

OSError: Unable to create file (unable to open file: name =
‘test.hdf5’, errno = 17, error message = ‘File exists’, flags = 15,
o_flags = c2)

我想通过检查文件是否已在写入模式下打开来解决此问题,如果是,请稍等一下再检查,直到它在写入模式下不再打开.我还没有找到任何h5py或hdf5的检查功能.截至目前,我的解决方案基于此:

from time import sleep
import h5py

# Function handling the intelligent hdf5 file opening
def open_hdf5(filename, *args, **kwargs):
    while True:
        try:
            hdf5_file = h5py.File(filename, *args, **kwargs)
            break  # Success!
        except OSError:
            sleep(5)  # Wait a bit
    return hdf5_file

# How to use the function
with open_hdf5(filename, mode='a') as hdf5_file:
    # Do stuff
    ...

我不确定我是否喜欢这个,因为它看起来不是很温和.有没有更好的方法呢?我的错误尝试在try中打开文件是否会以某种方式破坏其他进程中正在进行的写入过程?

最佳答案 通过快速研究判断,没有平台独立的方式来检查文件是否已经是开放写入模式.

How to check whether a file is_open and the open_status in python

https://bytes.com/topic/python/answers/612924-how-check-whether-file-open-not

但是,由于您已经定义了用于读取写入hdf5文件的包装器打开读/写方法,因此当您有一个成功打开hdf5文件的进程时,您始终可以创建“file_name”.lock文件.

然后你要做的就是使用os.path.exists(‘“file_name”.lock’)来知道你是否可以在写模式下打开文件.

基本上它与你所做的并没有太大的不同.然而,首先只是你可以查看你的filesytem来查看你的一个进程是否以写模式访问该文件,其次测试不是异常的产物,因为os.path.exists将返回一个布尔值.

许多应用程序都使用这种技巧.漫游CVS回购时,你经常会看到.lock文件在…

点赞