Skip to content

Commit 2a9416d

Browse files
authored
fix: catch exception on file open and release handle (#117)
1 parent f2fc113 commit 2a9416d

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

src/nd2/_sdk/latest.pyx

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,16 +73,27 @@ cdef class ND2Reader:
7373
self._fh = Lim_FileOpenForReadUtf8(self.path)
7474
if not self._fh:
7575
raise OSError("Could not open file: %s" % self.path)
76-
self._is_open = 1
76+
77+
# https://github.com/tlambert03/nd2/issues/114
78+
try:
79+
attrs = self._attributes()
80+
comp_type = attrs.get('compressionType')
81+
except Exception:
82+
Lim_FileClose(self._fh)
83+
raise OSError("Unknown error reading attributes in file: %s" % self.path)
84+
if not len(attrs) >= 6:
85+
Lim_FileClose(self._fh)
86+
raise OSError("Unknown error reading attributes in file: %s" % self.path)
7787

7888
if self._wants_read_using_sdk is None:
79-
self._read_using_sdk = self.attributes.compressionType is not None
89+
self._read_using_sdk = comp_type is not None
8090
else:
8191
self._read_using_sdk = self._wants_read_using_sdk
82-
if self.attributes.compressionType is not None and self._wants_read_using_sdk is False:
92+
if comp_type is not None and self._wants_read_using_sdk is False:
8393
Lim_FileClose(self._fh)
8494
raise ValueError("Cannot read compressed nd2 files with `read_using_sdk=False`")
8595

96+
self._is_open = 1
8697
if not self._read_using_sdk:
8798
with open(self.path, 'rb') as fh:
8899
self._mmap = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ)
@@ -111,6 +122,8 @@ cdef class ND2Reader:
111122
raise ValueError("Attempt to get attributes from closed nd2 file")
112123
cont = self._metadata().get('contents')
113124
attrs = self._attributes()
125+
if len(attrs) < 6:
126+
raise ValueError("Unexpected error reading attributes from file with SDK")
114127
nC = cont.get('channelCount') if cont else attrs.get("componentCount", 1)
115128
self.__attributes = structures.Attributes(**attrs, channelCount=nC)
116129
return self.__attributes

0 commit comments

Comments
 (0)