Skip to content

Commit 5e0bca3

Browse files
authored
Merge pull request #112 from CellProfiler/issues/4606
Close h5py file if needed
2 parents ca6c66b + de66577 commit 5e0bca3

File tree

1 file changed

+20
-7
lines changed

1 file changed

+20
-7
lines changed

cellprofiler_core/utilities/hdf5_dict.py

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -149,8 +149,8 @@ def __init__(
149149
from different CellProfiler runs by using a different
150150
run group name. If you open the file as
151151
"""
152-
assert mode in ("r", "r+", "w", "w+", "w-", "a")
153-
open_mode = mode
152+
assert mode in ("r", "r+", "w", "x", "w-", "a")
153+
self.mode = mode
154154
file_exists = (hdf5_filename is not None) and os.path.exists(hdf5_filename)
155155
default_run_group_name = time.strftime("%Y-%m-%d-%H-%m-%S")
156156
if mode in ("r", "r+"):
@@ -160,8 +160,6 @@ def __init__(
160160
else:
161161
load_measurements = False
162162
run_group_name = default_run_group_name
163-
if mode == "w+" and file_exists:
164-
open_mode = "r+"
165163

166164
self.is_temporary = is_temporary and (hdf5_filename is not None)
167165
self.filename = hdf5_filename
@@ -171,7 +169,7 @@ def __init__(
171169
self.filename,
172170
self.is_temporary,
173171
copy,
174-
open_mode,
172+
mode,
175173
)
176174
if self.filename is None:
177175
# core driver requires a unique filename even if the file
@@ -386,8 +384,23 @@ def flush(self):
386384
def file_contents(self):
387385
with self.lock:
388386
self.flush()
389-
with open(self.filename, "rb") as f:
390-
return memoryview(f.read())
387+
try:
388+
with open(self.filename, "rb") as f:
389+
return memoryview(f.read())
390+
except PermissionError:
391+
self.hdf5_file.close()
392+
with open(self.filename, "rb") as f:
393+
mem = memoryview(f.read())
394+
if 'w' not in self.mode:
395+
self.hdf5_file = h5py.File(self.filename, mode=self.mode)
396+
else:
397+
self.hdf5_file = h5py.File(self.filename, mode="a")
398+
399+
#We need to reopen the old group, not just the old file
400+
mgroup = self.hdf5_file[self.top_level_group_name]
401+
run_group_name = sorted(mgroup.keys())[-1]
402+
self.top_group = mgroup[run_group_name]
403+
return mem
391404

392405
@classmethod
393406
def has_hdf5_dict(cls, h5file):

0 commit comments

Comments
 (0)