/usr/lib/python3/dist-packages/pyvisa/ctwrapper/highlevel.py is in python3-pyvisa 1.8-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 | # -*- coding: utf-8 -*-
"""
pyvisa.ctwrapper.highlevel
~~~~~~~~~~~~~~~~~~~~~~~~~~
Highlevel wrapper of the VISA Library.
This file is part of PyVISA.
:copyright: 2014 by PyVISA Authors, see AUTHORS for more details.
:license: MIT, see LICENSE for more details.
"""
from __future__ import division, unicode_literals, print_function, absolute_import
import logging
import warnings
from pyvisa import constants, errors, highlevel, logger
from pyvisa.compat import integer_types, OrderedDict
from .cthelper import Library, find_library
from . import functions
logger = logging.LoggerAdapter(logger, {'backend': 'ni'})
def add_visa_methods(aclass):
for method in functions.visa_functions:
setattr(aclass, method, getattr(functions, method))
return aclass
def _args_to_str(args):
out = []
for arg in args:
try:
# noinspection PyProtectedMember
out.append(str(arg._obj))
except AttributeError:
out.append(arg)
return tuple(out)
@add_visa_methods
class NIVisaLibrary(highlevel.VisaLibraryBase):
"""High level NI-VISA Library wrapper using ctypes.
The easiest way to instantiate the library is to let `pyvisa` find the
right one for you. This looks first in your configuration file (~/.pyvisarc).
If it fails, it uses `ctypes.util.find_library` to try to locate a library
in a way similar to what the compiler does:
>>> visa_library = NIVisaLibrary()
But you can also specify the path:
>>> visa_library = NIVisaLibrary('/my/path/visa.so')
:param library_path: path of the VISA library.
"""
@staticmethod
def get_library_paths():
"""Return a tuple of possible library paths.
:rtype: tuple
"""
from ..util import LibraryPath, read_user_library_path
user_lib = read_user_library_path()
tmp = [find_library(library_path)
for library_path in ('visa', 'visa32', 'visa32.dll')]
tmp = [LibraryPath(library_path)
for library_path in tmp
if library_path is not None]
logger.debug('Automatically found library files: %s' % tmp)
if user_lib:
user_lib = LibraryPath(user_lib, 'user')
try:
tmp.remove(user_lib)
except ValueError:
pass
tmp.insert(0, user_lib)
return tuple(tmp)
@staticmethod
def get_debug_info():
"""Return a list of lines with backend info.
"""
from pyvisa import __version__
d = OrderedDict()
d['Version'] = '%s (bundled with PyVISA)' % __version__
paths = NIVisaLibrary.get_library_paths()
for ndx, visalib in enumerate(paths, 1):
nfo = OrderedDict()
nfo['found by'] = visalib.found_by
nfo['bitness'] = visalib.bitness
try:
lib = NIVisaLibrary(visalib)
sess, _ = lib.open_default_resource_manager()
nfo['Vendor'] = str(lib.get_attribute(sess, constants.VI_ATTR_RSRC_MANF_NAME)[0])
nfo['Impl. Version'] = str(lib.get_attribute(sess, constants.VI_ATTR_RSRC_IMPL_VERSION)[0])
nfo['Spec. Version'] = str(lib.get_attribute(sess, constants.VI_ATTR_RSRC_SPEC_VERSION)[0])
lib.close(sess)
except Exception as e:
e = str(e)
if 'No matching architecture' in e:
nfo['Could not get more info'] = 'Interpreter and library have different bitness.'
else:
nfo['Could not get more info'] = str(e).split('\n')
d['#%d: %s' % (ndx, visalib)] = nfo
if not paths:
d['Binary library'] = 'Not found'
return d
def _init(self):
try:
lib = Library(self.library_path)
except OSError as exc:
raise errors.LibraryError.from_exception(exc, self.library_path)
self.lib = lib
# Set the argtypes, restype and errcheck for each function
# of the visa library. Additionally store in `_functions` the
# name of the functions.
functions.set_signatures(self.lib, errcheck=self._return_handler)
logger.debug('Library signatures: %d ok, %d failed',
len(getattr(self.lib, '_functions', [])),
len(getattr(self.lib, '_functions_failed', [])))
# Set the library functions as attributes of the object.
for method_name in getattr(self.lib, '_functions', []):
setattr(self, method_name, getattr(self.lib, method_name))
def _return_handler(self, ret_value, func, arguments):
"""Check return values for errors and warnings.
"""
logger.debug('%s%s -> %r',
func.__name__, _args_to_str(arguments), ret_value,
extra=self._logging_extra)
try:
ret_value = constants.StatusCode(ret_value)
except ValueError:
pass
self._last_status = ret_value
# The first argument of almost all registered visa functions is a session.
# We store the error code per session
session = None
if func.__name__ not in ('viFindNext', ):
try:
session = arguments[0]
except KeyError:
raise Exception('Function %r does not seem to be a valid '
'visa function (len args %d)' % (func, len(arguments)))
# Functions that use the first parameter to get a session value.
if func.__name__ in ('viOpenDefaultRM', ):
# noinspection PyProtectedMember
session = session._obj.value
if isinstance(session, integer_types):
self._last_status_in_session[session] = ret_value
else:
# Functions that might or might have a session in the first argument.
if func.__name__ not in ('viClose', 'viGetAttribute', 'viSetAttribute', 'viStatusDesc'):
raise Exception('Function %r does not seem to be a valid '
'visa function (type args[0] %r)' % (func, type(session)))
if ret_value < 0:
raise errors.VisaIOError(ret_value)
if ret_value in self.issue_warning_on:
if session and ret_value not in self._ignore_warning_in_session[session]:
warnings.warn(errors.VisaIOWarning(ret_value), stacklevel=2)
return ret_value
def list_resources(self, session, query='?*::INSTR'):
"""Returns a tuple of all connected devices matching query.
:param query: regular expression used to match devices.
"""
resources = []
try:
find_list, return_counter, instrument_description, err = self.find_resources(session, query)
except errors.VisaIOError as e:
if e.error_code == constants.StatusCode.error_resource_not_found:
return tuple()
raise e
resources.append(instrument_description)
for i in range(return_counter - 1):
resources.append(self.find_next(find_list)[0])
self.close(find_list)
return tuple(resource for resource in resources)
|