Skip to content

Commit 4e0691e

Browse files
committed
fix(bdv): improve XML metadata reading and error handling
* Improve syntax for python 2.7. * Ensure the Java reader is closed to free resources * Use log.exception for better error logging * Clean up unnecessary blank lines
1 parent 7c31194 commit 4e0691e

1 file changed

Lines changed: 17 additions & 6 deletions

File tree

src/imcflibs/imagej/bdv.py

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,13 @@
1717
FuseBigStitcherDatasetIntoOMETiffCommand,
1818
)
1919
from ij import IJ
20-
2120
from java.io import File, FileInputStream, InputStreamReader
2221
from javax.xml.parsers import DocumentBuilderFactory
2322
from org.xml.sax import InputSource
2423

2524
from .. import pathtools
2625
from ..log import LOG as log
2726

28-
2927
# internal template strings used in string formatting (note: the `"""@private"""`
3028
# pseudo-decorator is there to instruct [pdoc] to omit those variables when generating
3129
# API documentation):
@@ -1684,16 +1682,18 @@ def read_metadata_from_xml(xml_path):
16841682
# Use our robust XML parsing function
16851683
dbf = DocumentBuilderFactory.newInstance()
16861684
db = dbf.newDocumentBuilder()
1687-
# This is needed to fix some issues with the micron symbol in the xml file
1688-
reader = InputStreamReader(FileInputStream(File(xml_path)))
1689-
dom = db.parse(InputSource(reader))
16901685

16911686
# Initialize default values
16921687
nbr_chnl = 1
16931688
nbr_ill = 1
16941689
nbr_tp = 1
16951690

1691+
reader = None
16961692
try:
1693+
# This is needed to fix some issues with the micron symbol in the xml file
1694+
reader = InputStreamReader(FileInputStream(File(xml_path)))
1695+
dom = db.parse(InputSource(reader))
1696+
16971697
# Extract channel and illumination counts
16981698
nodeList = dom.getElementsByTagName("Attributes")
16991699
for i in range(nodeList.getLength()):
@@ -1718,7 +1718,18 @@ def read_metadata_from_xml(xml_path):
17181718
if last_nodes.getLength() > 0:
17191719
nbr_tp = int(last_nodes.item(0).getTextContent()) + 1
17201720
except Exception as e:
1721-
log.error("Error extracting metadata from XML: {0}".format(str(e)))
1721+
# log.exception includes the traceback when available
1722+
try:
1723+
log.exception("Error extracting metadata from XML: %s", e)
1724+
except Exception:
1725+
log.error("Error extracting metadata from XML: %s", str(e))
1726+
finally:
1727+
# Ensure the Java reader is closed to free resources
1728+
try:
1729+
if reader is not None:
1730+
reader.close()
1731+
except Exception:
1732+
pass
17221733

17231734
xml_metadata = {
17241735
"channels_count": nbr_chnl,

0 commit comments

Comments
 (0)