Skip to content

Commit

Permalink
Feat/close instruments (#376)
Browse files Browse the repository at this point in the history
* Allow intruments to be used as contextmanagers

* Add unittest

* Remove unused imports

Co-authored-by: chris.grace <chris.grace@mastodondesign.com>
  • Loading branch information
Gracecr and chris-grace-mastodon committed Nov 3, 2022
1 parent 26cab7d commit bf4e131
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 1 deletion.
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ install_requires =
pyusb>=1.0
pyvisa>=1.9
ruamel.yaml>=0.16,<0.17
typing_extensions>=4.0.1

[options.extras_require]
numpy = numpy
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,8 @@ def close(self):
Close connection to stdin
"""
try:
self._stdin.close()
if self._stdin is not None:
self._stdin.close()
except OSError:
pass

Expand Down
7 changes: 7 additions & 0 deletions src/instruments/abstract_instruments/instrument.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import collections
import socket
import struct
import typing_extensions
import urllib.parse as parse

from serial import SerialException
Expand Down Expand Up @@ -718,3 +719,9 @@ def open_file(cls, filename):
:return: Object representing the connected instrument.
"""
return cls(FileCommunicator(filename))

def __enter__(self) -> typing_extensions.Self:
return self

def __exit__(self, *exc):
self._file.__exit__(*exc)
7 changes: 7 additions & 0 deletions tests/test_base_instrument.py
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,13 @@ def test_instrument_open_from_uri_invalid_scheme():
_ = ik.Instrument.open_from_uri("foo://bar")


@mock.patch("instruments.abstract_instruments.comm.LoopbackCommunicator.close")
def test_instrument_context_manager(mock_close: mock.Mock):
with ik.Instrument.open_test():
pass
mock_close.assert_called()


# INIT TESTS


Expand Down

0 comments on commit bf4e131

Please sign in to comment.