我同时以不同进程运行相同的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的此类检查功能。目前,我的解决方案基于以下内容:
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
中打开文件会影响正在进行的其他进程的写入过程吗?