We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Rename pyvisa imports
In the upcoming pyvisa version, using `import visa` is being [deprecated](https://github.com/pyvisa/pyvisa/pull/448) to avoid a name clash with another package. We need to fix that in our codebase, too. This could also be behind the version comparison issues like #130

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pymeasure/adapters/visa.py`
Content:
```
1 #
2 # This file is part of the PyMeasure package.
3 #
4 # Copyright (c) 2013-2020 PyMeasure Developers
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a copy
7 # of this software and associated documentation files (the "Software"), to deal
8 # in the Software without restriction, including without limitation the rights
9 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 # copies of the Software, and to permit persons to whom the Software is
11 # furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 # THE SOFTWARE.
23 #
24 
25 import logging
26 
27 import copy
28 import visa
29 import numpy as np
30 from pkg_resources import parse_version
31 
32 from .adapter import Adapter
33 
34 log = logging.getLogger(__name__)
35 log.addHandler(logging.NullHandler())
36 
37 
38 # noinspection PyPep8Naming,PyUnresolvedReferences
39 class VISAAdapter(Adapter):
40     """ Adapter class for the VISA library using PyVISA to communicate
41     with instruments.
42 
43     :param resource: VISA resource name that identifies the address
44     :param visa_library: VisaLibrary Instance, path of the VISA library or VisaLibrary spec string (@py or @ni).
45                          if not given, the default for the platform will be used.
46     :param kwargs: Any valid key-word arguments for constructing a PyVISA instrument
47     """
48 
49     def __init__(self, resourceName, visa_library='', **kwargs):
50         if not VISAAdapter.has_supported_version():
51             raise NotImplementedError("Please upgrade PyVISA to version 1.8 or later.")
52 
53         if isinstance(resourceName, int):
54             resourceName = "GPIB0::%d::INSTR" % resourceName
55         super(VISAAdapter, self).__init__()
56         self.resource_name = resourceName
57         self.manager = visa.ResourceManager(visa_library)
58         safeKeywords = ['resource_name', 'timeout',
59                         'chunk_size', 'lock', 'query_delay', 'send_end',
60                         'values_format', 'read_termination', 'write_termination']
61         kwargsCopy = copy.deepcopy(kwargs)
62         for key in kwargsCopy:
63             if key not in safeKeywords:
64                 kwargs.pop(key)
65         self.connection = self.manager.get_instrument(
66             resourceName,
67             **kwargs
68         )
69 
70     @staticmethod
71     def has_supported_version():
72         """ Returns True if the PyVISA version is greater than 1.8 """
73         if hasattr(visa, '__version__'):
74             return parse_version(visa.__version__) >= parse_version('1.8')
75         else:
76             return False
77 
78     def __repr__(self):
79         return "<VISAAdapter(resource='%s')>" % self.connection.resourceName
80 
81     def write(self, command):
82         """ Writes a command to the instrument
83 
84         :param command: SCPI command string to be sent to the instrument
85         """
86         self.connection.write(command)
87 
88     def read(self):
89         """ Reads until the buffer is empty and returns the resulting
90         ASCII response
91 
92         :returns: String ASCII response of the instrument.
93         """
94         return self.connection.read()
95 
96     def read_bytes(self, size):
97         """ Reads specified number of bytes from the buffer and returns
98         the resulting ASCII response
99 
100         :param size: Number of bytes to read from the buffer
101         :returns: String ASCII response of the instrument.
102         """
103         return self.connection.read_bytes(size)
104 
105     def ask(self, command):
106         """ Writes the command to the instrument and returns the resulting
107         ASCII response
108 
109         :param command: SCPI command string to be sent to the instrument
110         :returns: String ASCII response of the instrument
111         """
112         return self.connection.query(command)
113 
114     def ask_values(self, command):
115         """ Writes a command to the instrument and returns a list of formatted
116         values from the result. The format of the return is configurated by
117         self.config().
118 
119         :param command: SCPI command to be sent to the instrument
120         :returns: Formatted response of the instrument.
121         """
122         return self.connection.query_values(command)
123 
124     def binary_values(self, command, header_bytes=0, dtype=np.float32):
125         """ Returns a numpy array from a query for binary data
126 
127         :param command: SCPI command to be sent to the instrument
128         :param header_bytes: Integer number of bytes to ignore in header
129         :param dtype: The NumPy data type to format the values with
130         :returns: NumPy array of values
131         """
132         self.connection.write(command)
133         binary = self.connection.read_raw()
134         header, data = binary[:header_bytes], binary[header_bytes:]
135         return np.fromstring(data, dtype=dtype)
136 
137     def config(self, is_binary=False, datatype='str',
138                container=np.array, converter='s',
139                separator=',', is_big_endian=False):
140         """ Configurate the format of data transfer to and from the instrument.
141 
142         :param is_binary: If True, data is in binary format, otherwise ASCII.
143         :param datatype: Data type.
144         :param container: Return format. Any callable/type that takes an iterable.
145         :param converter: String converter, used in dealing with ASCII data.
146         :param separator: Delimiter of a series of data in ASCII.
147         :param is_big_endian: Endianness.
148         """
149         self.connection.values_format.is_binary = is_binary
150         self.connection.values_format.datatype = datatype
151         self.connection.values_format.container = container
152         self.connection.values_format.converter = converter
153         self.connection.values_format.separator = separator
154         self.connection.values_format.is_big_endian = is_big_endian
155 
156     def wait_for_srq(self, timeout=25, delay=0.1):
157         """ Blocks until a SRQ, and leaves the bit high
158 
159         :param timeout: Timeout duration in seconds
160         :param delay: Time delay between checking SRQ in seconds
161         """
162         self.connection.wait_for_srq(timeout * 1000)
163
```

Path: `pymeasure/instruments/resources.py`
Content:
```
1 #
2 # This file is part of the PyMeasure package.
3 #
4 # Copyright (c) 2013-2020 PyMeasure Developers
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a copy
7 # of this software and associated documentation files (the "Software"), to deal
8 # in the Software without restriction, including without limitation the rights
9 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 # copies of the Software, and to permit persons to whom the Software is
11 # furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 # THE SOFTWARE.
23 #
24 
25 import visa
26 
27 
28 def list_resources():
29     """
30     Prints the available resources, and returns a list of VISA resource names
31     
32     .. code-block:: python
33 
34         resources = list_resources()
35         #prints (e.g.)
36             #0 : GPIB0::22::INSTR : Agilent Technologies,34410A,******
37             #1 : GPIB0::26::INSTR : Keithley Instruments Inc., Model 2612, *****
38         dmm = Agilent34410(resources[0])
39     
40     """
41     rm = visa.ResourceManager()
42     instrs = rm.list_resources()
43     for n, instr in enumerate(instrs):
44         # trying to catch errors in comunication
45         try:
46             res = rm.open_resource(instr)
47             # try to avoid errors from *idn?
48             try:
49                 # noinspection PyUnresolvedReferences
50                 idn = res.ask('*idn?')[:-1]
51             except visa.Error:
52                 idn = "Not known"
53             finally:
54                 res.close()
55                 print(n, ":", instr, ":", idn)
56         except visa.VisaIOError as e:
57             print(n, ":", instr, ":", "Visa IO Error: check connections")
58             print(e)
59     rm.close()
60     return instrs
61
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/pymeasure/adapters/visa.py b/pymeasure/adapters/visa.py
--- a/pymeasure/adapters/visa.py
+++ b/pymeasure/adapters/visa.py
@@ -25,7 +25,7 @@
 import logging
 
 import copy
-import visa
+import pyvisa
 import numpy as np
 from pkg_resources import parse_version
 
@@ -54,7 +54,7 @@
             resourceName = "GPIB0::%d::INSTR" % resourceName
         super(VISAAdapter, self).__init__()
         self.resource_name = resourceName
-        self.manager = visa.ResourceManager(visa_library)
+        self.manager = pyvisa.ResourceManager(visa_library)
         safeKeywords = ['resource_name', 'timeout',
                         'chunk_size', 'lock', 'query_delay', 'send_end',
                         'values_format', 'read_termination', 'write_termination']
@@ -70,8 +70,8 @@
     @staticmethod
     def has_supported_version():
         """ Returns True if the PyVISA version is greater than 1.8 """
-        if hasattr(visa, '__version__'):
-            return parse_version(visa.__version__) >= parse_version('1.8')
+        if hasattr(pyvisa, '__version__'):
+            return parse_version(pyvisa.__version__) >= parse_version('1.8')
         else:
             return False
 
diff --git a/pymeasure/instruments/resources.py b/pymeasure/instruments/resources.py
--- a/pymeasure/instruments/resources.py
+++ b/pymeasure/instruments/resources.py
@@ -22,7 +22,7 @@
 # THE SOFTWARE.
 #
 
-import visa
+import pyvisa
 
 
 def list_resources():
@@ -38,7 +38,7 @@
         dmm = Agilent34410(resources[0])
     
     """
-    rm = visa.ResourceManager()
+    rm = pyvisa.ResourceManager()
     instrs = rm.list_resources()
     for n, instr in enumerate(instrs):
         # trying to catch errors in comunication
@@ -48,12 +48,12 @@
             try:
                 # noinspection PyUnresolvedReferences
                 idn = res.ask('*idn?')[:-1]
-            except visa.Error:
+            except pyvisa.Error:
                 idn = "Not known"
             finally:
                 res.close()
                 print(n, ":", instr, ":", idn)
-        except visa.VisaIOError as e:
+        except pyvisa.VisaIOError as e:
             print(n, ":", instr, ":", "Visa IO Error: check connections")
             print(e)
     rm.close()

{"golden_diff": "diff --git a/pymeasure/adapters/visa.py b/pymeasure/adapters/visa.py\n--- a/pymeasure/adapters/visa.py\n+++ b/pymeasure/adapters/visa.py\n@@ -25,7 +25,7 @@\n import logging\n \n import copy\n-import visa\n+import pyvisa\n import numpy as np\n from pkg_resources import parse_version\n \n@@ -54,7 +54,7 @@\n             resourceName = \"GPIB0::%d::INSTR\" % resourceName\n         super(VISAAdapter, self).__init__()\n         self.resource_name = resourceName\n-        self.manager = visa.ResourceManager(visa_library)\n+        self.manager = pyvisa.ResourceManager(visa_library)\n         safeKeywords = ['resource_name', 'timeout',\n                         'chunk_size', 'lock', 'query_delay', 'send_end',\n                         'values_format', 'read_termination', 'write_termination']\n@@ -70,8 +70,8 @@\n     @staticmethod\n     def has_supported_version():\n         \"\"\" Returns True if the PyVISA version is greater than 1.8 \"\"\"\n-        if hasattr(visa, '__version__'):\n-            return parse_version(visa.__version__) >= parse_version('1.8')\n+        if hasattr(pyvisa, '__version__'):\n+            return parse_version(pyvisa.__version__) >= parse_version('1.8')\n         else:\n             return False\n \ndiff --git a/pymeasure/instruments/resources.py b/pymeasure/instruments/resources.py\n--- a/pymeasure/instruments/resources.py\n+++ b/pymeasure/instruments/resources.py\n@@ -22,7 +22,7 @@\n # THE SOFTWARE.\n #\n \n-import visa\n+import pyvisa\n \n \n def list_resources():\n@@ -38,7 +38,7 @@\n         dmm = Agilent34410(resources[0])\n     \n     \"\"\"\n-    rm = visa.ResourceManager()\n+    rm = pyvisa.ResourceManager()\n     instrs = rm.list_resources()\n     for n, instr in enumerate(instrs):\n         # trying to catch errors in comunication\n@@ -48,12 +48,12 @@\n             try:\n                 # noinspection PyUnresolvedReferences\n                 idn = res.ask('*idn?')[:-1]\n-            except visa.Error:\n+            except pyvisa.Error:\n                 idn = \"Not known\"\n             finally:\n                 res.close()\n                 print(n, \":\", instr, \":\", idn)\n-        except visa.VisaIOError as e:\n+        except pyvisa.VisaIOError as e:\n             print(n, \":\", instr, \":\", \"Visa IO Error: check connections\")\n             print(e)\n     rm.close()\n", "issue": "Rename pyvisa imports\nIn the upcoming pyvisa version, using `import visa` is being [deprecated](https://github.com/pyvisa/pyvisa/pull/448) to avoid a name clash with another package. We need to fix that in our codebase, too. This could also be behind the version comparison issues like #130\n", "before_files": [{"content": "#\n# This file is part of the PyMeasure package.\n#\n# Copyright (c) 2013-2020 PyMeasure Developers\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n\nimport logging\n\nimport copy\nimport visa\nimport numpy as np\nfrom pkg_resources import parse_version\n\nfrom .adapter import Adapter\n\nlog = logging.getLogger(__name__)\nlog.addHandler(logging.NullHandler())\n\n\n# noinspection PyPep8Naming,PyUnresolvedReferences\nclass VISAAdapter(Adapter):\n    \"\"\" Adapter class for the VISA library using PyVISA to communicate\n    with instruments.\n\n    :param resource: VISA resource name that identifies the address\n    :param visa_library: VisaLibrary Instance, path of the VISA library or VisaLibrary spec string (@py or @ni).\n                         if not given, the default for the platform will be used.\n    :param kwargs: Any valid key-word arguments for constructing a PyVISA instrument\n    \"\"\"\n\n    def __init__(self, resourceName, visa_library='', **kwargs):\n        if not VISAAdapter.has_supported_version():\n            raise NotImplementedError(\"Please upgrade PyVISA to version 1.8 or later.\")\n\n        if isinstance(resourceName, int):\n            resourceName = \"GPIB0::%d::INSTR\" % resourceName\n        super(VISAAdapter, self).__init__()\n        self.resource_name = resourceName\n        self.manager = visa.ResourceManager(visa_library)\n        safeKeywords = ['resource_name', 'timeout',\n                        'chunk_size', 'lock', 'query_delay', 'send_end',\n                        'values_format', 'read_termination', 'write_termination']\n        kwargsCopy = copy.deepcopy(kwargs)\n        for key in kwargsCopy:\n            if key not in safeKeywords:\n                kwargs.pop(key)\n        self.connection = self.manager.get_instrument(\n            resourceName,\n            **kwargs\n        )\n\n    @staticmethod\n    def has_supported_version():\n        \"\"\" Returns True if the PyVISA version is greater than 1.8 \"\"\"\n        if hasattr(visa, '__version__'):\n            return parse_version(visa.__version__) >= parse_version('1.8')\n        else:\n            return False\n\n    def __repr__(self):\n        return \"<VISAAdapter(resource='%s')>\" % self.connection.resourceName\n\n    def write(self, command):\n        \"\"\" Writes a command to the instrument\n\n        :param command: SCPI command string to be sent to the instrument\n        \"\"\"\n        self.connection.write(command)\n\n    def read(self):\n        \"\"\" Reads until the buffer is empty and returns the resulting\n        ASCII response\n\n        :returns: String ASCII response of the instrument.\n        \"\"\"\n        return self.connection.read()\n\n    def read_bytes(self, size):\n        \"\"\" Reads specified number of bytes from the buffer and returns\n        the resulting ASCII response\n\n        :param size: Number of bytes to read from the buffer\n        :returns: String ASCII response of the instrument.\n        \"\"\"\n        return self.connection.read_bytes(size)\n\n    def ask(self, command):\n        \"\"\" Writes the command to the instrument and returns the resulting\n        ASCII response\n\n        :param command: SCPI command string to be sent to the instrument\n        :returns: String ASCII response of the instrument\n        \"\"\"\n        return self.connection.query(command)\n\n    def ask_values(self, command):\n        \"\"\" Writes a command to the instrument and returns a list of formatted\n        values from the result. The format of the return is configurated by\n        self.config().\n\n        :param command: SCPI command to be sent to the instrument\n        :returns: Formatted response of the instrument.\n        \"\"\"\n        return self.connection.query_values(command)\n\n    def binary_values(self, command, header_bytes=0, dtype=np.float32):\n        \"\"\" Returns a numpy array from a query for binary data\n\n        :param command: SCPI command to be sent to the instrument\n        :param header_bytes: Integer number of bytes to ignore in header\n        :param dtype: The NumPy data type to format the values with\n        :returns: NumPy array of values\n        \"\"\"\n        self.connection.write(command)\n        binary = self.connection.read_raw()\n        header, data = binary[:header_bytes], binary[header_bytes:]\n        return np.fromstring(data, dtype=dtype)\n\n    def config(self, is_binary=False, datatype='str',\n               container=np.array, converter='s',\n               separator=',', is_big_endian=False):\n        \"\"\" Configurate the format of data transfer to and from the instrument.\n\n        :param is_binary: If True, data is in binary format, otherwise ASCII.\n        :param datatype: Data type.\n        :param container: Return format. Any callable/type that takes an iterable.\n        :param converter: String converter, used in dealing with ASCII data.\n        :param separator: Delimiter of a series of data in ASCII.\n        :param is_big_endian: Endianness.\n        \"\"\"\n        self.connection.values_format.is_binary = is_binary\n        self.connection.values_format.datatype = datatype\n        self.connection.values_format.container = container\n        self.connection.values_format.converter = converter\n        self.connection.values_format.separator = separator\n        self.connection.values_format.is_big_endian = is_big_endian\n\n    def wait_for_srq(self, timeout=25, delay=0.1):\n        \"\"\" Blocks until a SRQ, and leaves the bit high\n\n        :param timeout: Timeout duration in seconds\n        :param delay: Time delay between checking SRQ in seconds\n        \"\"\"\n        self.connection.wait_for_srq(timeout * 1000)\n", "path": "pymeasure/adapters/visa.py"}, {"content": "#\n# This file is part of the PyMeasure package.\n#\n# Copyright (c) 2013-2020 PyMeasure Developers\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n\nimport visa\n\n\ndef list_resources():\n    \"\"\"\n    Prints the available resources, and returns a list of VISA resource names\n    \n    .. code-block:: python\n\n        resources = list_resources()\n        #prints (e.g.)\n            #0 : GPIB0::22::INSTR : Agilent Technologies,34410A,******\n            #1 : GPIB0::26::INSTR : Keithley Instruments Inc., Model 2612, *****\n        dmm = Agilent34410(resources[0])\n    \n    \"\"\"\n    rm = visa.ResourceManager()\n    instrs = rm.list_resources()\n    for n, instr in enumerate(instrs):\n        # trying to catch errors in comunication\n        try:\n            res = rm.open_resource(instr)\n            # try to avoid errors from *idn?\n            try:\n                # noinspection PyUnresolvedReferences\n                idn = res.ask('*idn?')[:-1]\n            except visa.Error:\n                idn = \"Not known\"\n            finally:\n                res.close()\n                print(n, \":\", instr, \":\", idn)\n        except visa.VisaIOError as e:\n            print(n, \":\", instr, \":\", \"Visa IO Error: check connections\")\n            print(e)\n    rm.close()\n    return instrs\n", "path": "pymeasure/instruments/resources.py"}], "after_files": [{"content": "#\n# This file is part of the PyMeasure package.\n#\n# Copyright (c) 2013-2020 PyMeasure Developers\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n\nimport logging\n\nimport copy\nimport pyvisa\nimport numpy as np\nfrom pkg_resources import parse_version\n\nfrom .adapter import Adapter\n\nlog = logging.getLogger(__name__)\nlog.addHandler(logging.NullHandler())\n\n\n# noinspection PyPep8Naming,PyUnresolvedReferences\nclass VISAAdapter(Adapter):\n    \"\"\" Adapter class for the VISA library using PyVISA to communicate\n    with instruments.\n\n    :param resource: VISA resource name that identifies the address\n    :param visa_library: VisaLibrary Instance, path of the VISA library or VisaLibrary spec string (@py or @ni).\n                         if not given, the default for the platform will be used.\n    :param kwargs: Any valid key-word arguments for constructing a PyVISA instrument\n    \"\"\"\n\n    def __init__(self, resourceName, visa_library='', **kwargs):\n        if not VISAAdapter.has_supported_version():\n            raise NotImplementedError(\"Please upgrade PyVISA to version 1.8 or later.\")\n\n        if isinstance(resourceName, int):\n            resourceName = \"GPIB0::%d::INSTR\" % resourceName\n        super(VISAAdapter, self).__init__()\n        self.resource_name = resourceName\n        self.manager = pyvisa.ResourceManager(visa_library)\n        safeKeywords = ['resource_name', 'timeout',\n                        'chunk_size', 'lock', 'query_delay', 'send_end',\n                        'values_format', 'read_termination', 'write_termination']\n        kwargsCopy = copy.deepcopy(kwargs)\n        for key in kwargsCopy:\n            if key not in safeKeywords:\n                kwargs.pop(key)\n        self.connection = self.manager.get_instrument(\n            resourceName,\n            **kwargs\n        )\n\n    @staticmethod\n    def has_supported_version():\n        \"\"\" Returns True if the PyVISA version is greater than 1.8 \"\"\"\n        if hasattr(pyvisa, '__version__'):\n            return parse_version(pyvisa.__version__) >= parse_version('1.8')\n        else:\n            return False\n\n    def __repr__(self):\n        return \"<VISAAdapter(resource='%s')>\" % self.connection.resourceName\n\n    def write(self, command):\n        \"\"\" Writes a command to the instrument\n\n        :param command: SCPI command string to be sent to the instrument\n        \"\"\"\n        self.connection.write(command)\n\n    def read(self):\n        \"\"\" Reads until the buffer is empty and returns the resulting\n        ASCII response\n\n        :returns: String ASCII response of the instrument.\n        \"\"\"\n        return self.connection.read()\n\n    def read_bytes(self, size):\n        \"\"\" Reads specified number of bytes from the buffer and returns\n        the resulting ASCII response\n\n        :param size: Number of bytes to read from the buffer\n        :returns: String ASCII response of the instrument.\n        \"\"\"\n        return self.connection.read_bytes(size)\n\n    def ask(self, command):\n        \"\"\" Writes the command to the instrument and returns the resulting\n        ASCII response\n\n        :param command: SCPI command string to be sent to the instrument\n        :returns: String ASCII response of the instrument\n        \"\"\"\n        return self.connection.query(command)\n\n    def ask_values(self, command):\n        \"\"\" Writes a command to the instrument and returns a list of formatted\n        values from the result. The format of the return is configurated by\n        self.config().\n\n        :param command: SCPI command to be sent to the instrument\n        :returns: Formatted response of the instrument.\n        \"\"\"\n        return self.connection.query_values(command)\n\n    def binary_values(self, command, header_bytes=0, dtype=np.float32):\n        \"\"\" Returns a numpy array from a query for binary data\n\n        :param command: SCPI command to be sent to the instrument\n        :param header_bytes: Integer number of bytes to ignore in header\n        :param dtype: The NumPy data type to format the values with\n        :returns: NumPy array of values\n        \"\"\"\n        self.connection.write(command)\n        binary = self.connection.read_raw()\n        header, data = binary[:header_bytes], binary[header_bytes:]\n        return np.fromstring(data, dtype=dtype)\n\n    def config(self, is_binary=False, datatype='str',\n               container=np.array, converter='s',\n               separator=',', is_big_endian=False):\n        \"\"\" Configurate the format of data transfer to and from the instrument.\n\n        :param is_binary: If True, data is in binary format, otherwise ASCII.\n        :param datatype: Data type.\n        :param container: Return format. Any callable/type that takes an iterable.\n        :param converter: String converter, used in dealing with ASCII data.\n        :param separator: Delimiter of a series of data in ASCII.\n        :param is_big_endian: Endianness.\n        \"\"\"\n        self.connection.values_format.is_binary = is_binary\n        self.connection.values_format.datatype = datatype\n        self.connection.values_format.container = container\n        self.connection.values_format.converter = converter\n        self.connection.values_format.separator = separator\n        self.connection.values_format.is_big_endian = is_big_endian\n\n    def wait_for_srq(self, timeout=25, delay=0.1):\n        \"\"\" Blocks until a SRQ, and leaves the bit high\n\n        :param timeout: Timeout duration in seconds\n        :param delay: Time delay between checking SRQ in seconds\n        \"\"\"\n        self.connection.wait_for_srq(timeout * 1000)\n", "path": "pymeasure/adapters/visa.py"}, {"content": "#\n# This file is part of the PyMeasure package.\n#\n# Copyright (c) 2013-2020 PyMeasure Developers\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n\nimport pyvisa\n\n\ndef list_resources():\n    \"\"\"\n    Prints the available resources, and returns a list of VISA resource names\n    \n    .. code-block:: python\n\n        resources = list_resources()\n        #prints (e.g.)\n            #0 : GPIB0::22::INSTR : Agilent Technologies,34410A,******\n            #1 : GPIB0::26::INSTR : Keithley Instruments Inc., Model 2612, *****\n        dmm = Agilent34410(resources[0])\n    \n    \"\"\"\n    rm = pyvisa.ResourceManager()\n    instrs = rm.list_resources()\n    for n, instr in enumerate(instrs):\n        # trying to catch errors in comunication\n        try:\n            res = rm.open_resource(instr)\n            # try to avoid errors from *idn?\n            try:\n                # noinspection PyUnresolvedReferences\n                idn = res.ask('*idn?')[:-1]\n            except pyvisa.Error:\n                idn = \"Not known\"\n            finally:\n                res.close()\n                print(n, \":\", instr, \":\", idn)\n        except pyvisa.VisaIOError as e:\n            print(n, \":\", instr, \":\", \"Visa IO Error: check connections\")\n            print(e)\n    rm.close()\n    return instrs\n", "path": "pymeasure/instruments/resources.py"}]}