From a9ccdb19ce5c57730294e45017ad1c4e4ead1105 Mon Sep 17 00:00:00 2001 From: Jim Rybarski Date: Fri, 9 Oct 2015 22:18:12 -0500 Subject: [PATCH] resolves #96: added context manager --- README.md | 8 ++++++++ nd2reader/interface.py | 9 ++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 83cbd6b..65afe92 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,14 @@ You can also get some metadata about the nd2 programatically: 30528 ``` +`Nd2` is also a context manager, if you care about that sort of thing: + +``` +>>> import nd2reader +>>> with nd2reader.Nd2("/path/to/my_images.nd2") as nd2: +... for image in nd2: +... do_something(image) + ### Images `Image` objects are just Numpy arrays with some extra metadata bolted on: diff --git a/nd2reader/interface.py b/nd2reader/interface.py index 54d8607..9f3403b 100644 --- a/nd2reader/interface.py +++ b/nd2reader/interface.py @@ -12,12 +12,19 @@ class Nd2(object): """ def __init__(self, filename): + self._filename = filename self._fh = open(filename, "rb") major_version, minor_version = get_version(self._fh) parser = get_parser(self._fh, major_version, minor_version) self._driver = parser.driver self._metadata = parser.metadata - self._filename = filename + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._fh is not None: + self._fh.close() def __repr__(self): return "\n".join(["" % self._filename,