I run the same Python program concurrently as different processes, and these all want to write to the same hdf5
file, using the h5py
Python package. However, only a single process may open a given hdf5
file in write mode, otherwise you will get the error
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)
I want to resolve this by checking whether the file is already opened in write mode, and if so, wait a bit and check again, until it is no longer opened in write mode. I have not found any such checking capability of h5py
or hdf5
. As of now, my solution is based on this:
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
...
I'm unsure whether I like this, as it doesn't seem very gentle. Are there any better way of doing this? Are there any change that my erroneous attempts to open the file inside the try
can somehow corrupt the write process that is going on in the other process?