├── .gitignore ├── .travis.yml ├── AUTHORS ├── CHANGES ├── ChangeLog ├── LICENSE ├── MANIFEST.in ├── README ├── docs ├── LICENSE ├── Makefile ├── _static │ └── logo-full.jpg ├── api │ ├── constants.rst │ ├── index.rst │ ├── resourcemanager.rst │ ├── resources.rst │ └── visalibrarybase.rst ├── architecture.rst ├── backends.rst ├── conf.py ├── configuring.rst ├── contributing.rst ├── default.css ├── example.rst ├── faq.rst ├── getting.rst ├── getting_nivisa.rst ├── index.rst ├── make.bat ├── migrating.rst ├── names.rst ├── resources.rst ├── rvalues.rst ├── shell.rst └── tutorial.rst ├── examples ├── itc4.py └── keithley2000.py ├── pyvisa ├── __init__.py ├── attributes.py ├── compat │ ├── __init__.py │ ├── nullhandler.py │ ├── ordereddict.py │ └── struct.py ├── constants.py ├── ctwrapper │ ├── __init__.py │ ├── cthelper.py │ ├── functions.py │ ├── highlevel.py │ └── types.py ├── errors.py ├── highlevel.py ├── resources │ ├── __init__.py │ ├── firewire.py │ ├── gpib.py │ ├── messagebased.py │ ├── pxi.py │ ├── registerbased.py │ ├── resource.py │ ├── serial.py │ ├── tcpip.py │ ├── usb.py │ └── vxi.py ├── rname.py ├── shell.py ├── testsuite │ ├── __init__.py │ ├── test_errors.py │ ├── test_rname.py │ └── test_util.py ├── thirdparty │ ├── __init__.py │ └── prettytable.py └── util.py ├── setup.cfg ├── setup.py ├── tox.ini └── visa.py /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | __pycache__ 3 | *egg-info* 4 | *.pyc 5 | .DS_Store 6 | docs/_build/ 7 | .idea 8 | build/ 9 | dist/ 10 | MANIFEST 11 | .tox 12 | .coveragerc 13 | # WebDAV file system cache files 14 | .DAV/ 15 | _test/ 16 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | branches: 4 | only: 5 | # This is where pull requests from "bors r+" are built. 6 | - staging 7 | # This is where pull requests from "bors try" are built. 8 | - trying 9 | # Build master too 10 | - master 11 | 12 | python: 13 | - "2.7" 14 | - "3.4" 15 | - "3.5" 16 | - "3.6" 17 | 18 | install: 19 | - if [ $TRAVIS_PYTHON_VERSION == '2.7' ] || [ $TRAVIS_PYTHON_VERSION == '3.6' ]; then pip install numpy; fi 20 | - pip install coverage coveralls 21 | 22 | script: 23 | - coverage run -p --source=pyvisa --omit="*test*","*compat*" setup.py test 24 | - coverage combine 25 | - coverage report -m 26 | 27 | after_script: 28 | - coveralls --verbose 29 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | PyVISA was originally programmed by Torsten Bronger and Gregor Thalhammer, Innsbruck, Austria. It is based on earlier experiences by Thalhammer. 2 | 3 | It was maintained from March 2012 to August 2013 by Florian Bauer. 4 | It is currently maintained by Hernan E. Grecco . 5 | 6 | Other contributors, listed alphabetically, are: 7 | 8 | * bauflo3 9 | * bkstein 10 | * bronger> 11 | * Christian Lupien 12 | * Colin Marquardt 13 | * crazyfermions 14 | * gnbl 15 | * Gregor Thalhammer 16 | * HummingBrid 17 | * kcsaff 18 | * Laurent P. René de Cotret 19 | * Martin Ritter 20 | * Matthew94 21 | * Matthieu Dartiailh 22 | * mordoror 23 | * Tobias Müller 24 | * Yves Delley 25 | 26 | If you think your name should be here, please let me know. 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License 2 | 3 | Copyright (c) 2005-2014 PyVISA Authors and contributors. See AUTHORS 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 9 | of the Software, and to permit persons to whom the Software is furnished to do 10 | so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README AUTHORS CHANGES LICENSE ChangeLog 2 | recursive-include pyvisa * 3 | recursive-include docs * 4 | recursive-include examples * 5 | prune docs/_build 6 | prune docs/_themes/.git 7 | global-exclude *.pyc *~ .DS_Store *__pycache__* *.pyo 8 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | PyVISA 2 | ====== 3 | 4 | A Python package for support of the "Virtual Instrument Software 5 | Architecture" (VISA), in order to control measurement devices and 6 | test equipment via GPIB, RS232, Ethernet or USB. 7 | 8 | 9 | Description 10 | ----------- 11 | 12 | The programming of measurement instruments can be real pain. There are many 13 | different protocols, sent over many different interfaces and bus systems 14 | (GPIB, RS232, USB). For every programming language you want to use, you have to 15 | find libraries that support both your device and its bus system. 16 | 17 | In order to ease this unfortunate situation, the Virtual Instrument Software 18 | Architecture (VISA_) specification was defined in the middle of the 90'. Today 19 | VISA is implemented on all significant operating systems. A couple of vendors 20 | offer VISA libraries, partly with free download. These libraries work together 21 | with arbitrary peripheral devices, although they may be limited to certain 22 | interface devices, such as the vendor’s GPIB card. 23 | 24 | The VISA specification has explicit bindings to Visual Basic, C, and G 25 | (LabVIEW’s graphical language). Python can be used to call functions from a 26 | VISA shared library (`.dll`, `.so`, `.dylib`) allowing to directly leverage the 27 | standard implementations. In addition, Python can be used to directly access 28 | most bus systems used by instruments which is why one can envision to implement 29 | the VISA standard directly in Python (see the `PyVISA-Py` project for more 30 | details). PyVISA is both a Python wrapper for VISA shared libraries but 31 | can also serve as a front-end for other VISA implementation such as 32 | `PyVISA-Py`. 33 | 34 | 35 | .. _VISA: http://www.ivifoundation.org/specifications/default.aspx 36 | .. _`PyVISA-Py`: http://pyvisa-py.readthedocs.io/en/latest/ 37 | 38 | 39 | VISA and Python 40 | --------------- 41 | 42 | Python has a couple of features that make it very interesting for measurement 43 | controlling: 44 | 45 | - Python is an easy-to-learn scripting language with short development cycles. 46 | - It represents a high abstraction level [2], which perfectly blends with the 47 | abstraction level of measurement programs. 48 | - It has a very rich set of native libraries, including numerical and plotting 49 | modules for data analysis and visualisation. 50 | - A large set of books (in many languages) and on-line publications is 51 | available. 52 | 53 | 54 | Requirements 55 | ------------ 56 | 57 | - Python (tested with 2.7 and 3.4+) 58 | - VISA (tested with NI-VISA 17.5, Win7, from www.ni.com/visa) 59 | 60 | 61 | Installation 62 | -------------- 63 | 64 | Using pip: 65 | 66 | $ pip install pyvisa 67 | 68 | or easy_install: 69 | 70 | $ easy_install pyvisa 71 | 72 | or download and unzip the source distribution file and: 73 | 74 | $ python setup.py install 75 | 76 | 77 | Documentation 78 | -------------- 79 | 80 | The documentation can be read online at https://pyvisa.readthedocs.org 81 | -------------------------------------------------------------------------------- /docs/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License 2 | 3 | Copyright (c) 2005, 2006, 2007, 2008 4 | Torsten Bronger , 5 | Gregor Thalhammer . 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining a copy of 8 | this software and associated documentation files (the "Software"), to deal in 9 | the Software without restriction, including without limitation the rights to 10 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 11 | of the Software, and to permit persons to whom the Software is furnished to do 12 | so, subject to the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be included in all 15 | copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23 | SOFTWARE. 24 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 16 | 17 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 18 | 19 | help: 20 | @echo "Please use \`make ' where is one of" 21 | @echo " html to make standalone HTML files" 22 | @echo " dirhtml to make HTML files named index.html in directories" 23 | @echo " singlehtml to make a single large HTML file" 24 | @echo " pickle to make pickle files" 25 | @echo " json to make JSON files" 26 | @echo " htmlhelp to make HTML files and a HTML help project" 27 | @echo " qthelp to make HTML files and a qthelp project" 28 | @echo " devhelp to make HTML files and a Devhelp project" 29 | @echo " epub to make an epub" 30 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 31 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 32 | @echo " text to make text files" 33 | @echo " man to make manual pages" 34 | @echo " texinfo to make Texinfo files" 35 | @echo " info to make Texinfo files and run them through makeinfo" 36 | @echo " gettext to make PO message catalogs" 37 | @echo " changes to make an overview of all changed/added/deprecated items" 38 | @echo " linkcheck to check all external links for integrity" 39 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 40 | 41 | clean: 42 | -rm -rf $(BUILDDIR)/* 43 | 44 | html: 45 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 48 | 49 | dirhtml: 50 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 51 | @echo 52 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 53 | 54 | singlehtml: 55 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 56 | @echo 57 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 58 | 59 | pickle: 60 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 61 | @echo 62 | @echo "Build finished; now you can process the pickle files." 63 | 64 | json: 65 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 66 | @echo 67 | @echo "Build finished; now you can process the JSON files." 68 | 69 | htmlhelp: 70 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 71 | @echo 72 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 73 | ".hhp project file in $(BUILDDIR)/htmlhelp." 74 | 75 | qthelp: 76 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 77 | @echo 78 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 79 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 80 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pyvisa.qhcp" 81 | @echo "To view the help file:" 82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pyvisa.qhc" 83 | 84 | devhelp: 85 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 86 | @echo 87 | @echo "Build finished." 88 | @echo "To view the help file:" 89 | @echo "# mkdir -p $$HOME/.local/share/devhelp/pyvisa" 90 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pyvisa" 91 | @echo "# devhelp" 92 | 93 | epub: 94 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 95 | @echo 96 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 97 | 98 | latex: 99 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 100 | @echo 101 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 102 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 103 | "(use \`make latexpdf' here to do that automatically)." 104 | 105 | latexpdf: 106 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 107 | @echo "Running LaTeX files through pdflatex..." 108 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 109 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 110 | 111 | text: 112 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 113 | @echo 114 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 115 | 116 | man: 117 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 118 | @echo 119 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 120 | 121 | texinfo: 122 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 123 | @echo 124 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 125 | @echo "Run \`make' in that directory to run these through makeinfo" \ 126 | "(use \`make info' here to do that automatically)." 127 | 128 | info: 129 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 130 | @echo "Running Texinfo files through makeinfo..." 131 | make -C $(BUILDDIR)/texinfo info 132 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 133 | 134 | gettext: 135 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 136 | @echo 137 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 138 | 139 | changes: 140 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 141 | @echo 142 | @echo "The overview file is in $(BUILDDIR)/changes." 143 | 144 | linkcheck: 145 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 146 | @echo 147 | @echo "Link check complete; look for any errors in the above output " \ 148 | "or in $(BUILDDIR)/linkcheck/output.txt." 149 | 150 | doctest: 151 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 152 | @echo "Testing of doctests in the sources finished, look at the " \ 153 | "results in $(BUILDDIR)/doctest/output.txt." 154 | -------------------------------------------------------------------------------- /docs/_static/logo-full.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hgrecco/pyvisa/5522e02a965bcd48a0beff2756ea402570b97db4/docs/_static/logo-full.jpg -------------------------------------------------------------------------------- /docs/api/constants.rst: -------------------------------------------------------------------------------- 1 | .. _api_constants: 2 | 3 | Constants module 4 | ---------------- 5 | 6 | .. py:module:: pyvisa.constants 7 | 8 | Provides user-friendly naming to values used in different functions. 9 | 10 | 11 | .. autoclass:: AccessModes 12 | :members: 13 | :undoc-members: 14 | 15 | .. autoclass:: StopBits 16 | :members: 17 | :undoc-members: 18 | 19 | .. autoclass:: Parity 20 | :members: 21 | :undoc-members: 22 | 23 | .. autoclass:: SerialTermination 24 | :members: 25 | :undoc-members: 26 | 27 | .. autoclass:: InterfaceType 28 | :members: 29 | :undoc-members: 30 | 31 | .. autoclass:: AddressState 32 | :members: 33 | :undoc-members: 34 | 35 | .. autoclass:: IOProtocol 36 | :members: 37 | :undoc-members: 38 | 39 | .. autoclass:: LineState 40 | :members: 41 | :undoc-members: 42 | 43 | .. autoclass:: StatusCode 44 | :members: 45 | :undoc-members: 46 | -------------------------------------------------------------------------------- /docs/api/index.rst: -------------------------------------------------------------------------------- 1 | .. _api: 2 | 3 | === 4 | API 5 | === 6 | 7 | 8 | .. toctree:: 9 | :maxdepth: 1 10 | 11 | visalibrarybase 12 | resourcemanager 13 | resources 14 | constants 15 | -------------------------------------------------------------------------------- /docs/api/resourcemanager.rst: -------------------------------------------------------------------------------- 1 | .. _api_resourcemanager: 2 | 3 | Resource Manager 4 | ---------------- 5 | 6 | .. autoclass:: pyvisa.highlevel.ResourceInfo 7 | 8 | .. autoclass:: pyvisa.highlevel.ResourceManager 9 | :members: close, session, list_resources, list_resources_info, resource_info, open_bare_resource, open_resource, last_status 10 | -------------------------------------------------------------------------------- /docs/api/resources.rst: -------------------------------------------------------------------------------- 1 | .. _api_resources: 2 | 3 | Resource classes 4 | ---------------- 5 | 6 | Resources are high level abstractions to managing specific sessions. An instance 7 | of one of these classes is returned by the :meth:`~pyvisa.highlevel.ResourceManager.open_resource` 8 | depending on the resource type. 9 | 10 | Generic classes 11 | ~~~~~~~~~~~~~~~ 12 | 13 | - :class:`~pyvisa.resources.Resource` 14 | - :class:`~pyvisa.resources.MessageBasedResource` 15 | - :class:`~pyvisa.resources.RegisterBasedResource` 16 | 17 | 18 | Specific Classes 19 | ~~~~~~~~~~~~~~~~ 20 | 21 | - :class:`~pyvisa.resources.SerialInstrument` 22 | - :class:`~pyvisa.resources.TCPIPInstrument` 23 | - :class:`~pyvisa.resources.TCPIPSocket` 24 | - :class:`~pyvisa.resources.USBInstrument` 25 | - :class:`~pyvisa.resources.USBRaw` 26 | - :class:`~pyvisa.resources.GPIBInstrument` 27 | - :class:`~pyvisa.resources.GPIBInterface` 28 | - :class:`~pyvisa.resources.FirewireInstrument` 29 | - :class:`~pyvisa.resources.PXIInstrument` 30 | - :class:`~pyvisa.resources.PXIInstrument` 31 | - :class:`~pyvisa.resources.VXIInstrument` 32 | - :class:`~pyvisa.resources.VXIMemory` 33 | - :class:`~pyvisa.resources.VXIBackplane` 34 | 35 | .. currentmodule::`pyvisa.resources` 36 | 37 | 38 | .. autoclass:: pyvisa.resources.Resource 39 | :members: 40 | :inherited-members: 41 | :undoc-members: 42 | 43 | 44 | .. autoclass:: pyvisa.resources.MessageBasedResource 45 | :members: 46 | :inherited-members: 47 | :exclude-members: ask_delay, ask_for_values, ask 48 | :undoc-members: 49 | 50 | 51 | .. autoclass:: pyvisa.resources.RegisterBasedResource 52 | :members: 53 | :inherited-members: 54 | :undoc-members: 55 | 56 | 57 | .. autoclass:: pyvisa.resources.SerialInstrument 58 | :members: 59 | :inherited-members: 60 | :exclude-members: ask_delay, ask_for_values, ask 61 | :undoc-members: 62 | 63 | 64 | .. autoclass:: pyvisa.resources.TCPIPInstrument 65 | :members: 66 | :inherited-members: 67 | :exclude-members: ask_delay, ask_for_values, ask 68 | :undoc-members: 69 | 70 | .. autoclass:: pyvisa.resources.TCPIPSocket 71 | :members: 72 | :inherited-members: 73 | :exclude-members: ask_delay, ask_for_values, ask 74 | :undoc-members: 75 | 76 | .. autoclass:: pyvisa.resources.USBInstrument 77 | :members: 78 | :inherited-members: 79 | :exclude-members: ask_delay, ask_for_values, ask 80 | :undoc-members: 81 | 82 | .. autoclass:: pyvisa.resources.USBRaw 83 | :members: 84 | :inherited-members: 85 | :exclude-members: ask_delay, ask_for_values, ask 86 | :undoc-members: 87 | 88 | .. autoclass:: pyvisa.resources.GPIBInstrument 89 | :members: 90 | :inherited-members: 91 | :exclude-members: ask_delay, ask_for_values, ask 92 | :undoc-members: 93 | 94 | .. autoclass:: pyvisa.resources.GPIBInterface 95 | :members: 96 | :inherited-members: 97 | :exclude-members: ask_delay, ask_for_values, ask 98 | :undoc-members: 99 | 100 | .. autoclass:: pyvisa.resources.FirewireInstrument 101 | :members: 102 | :inherited-members: 103 | :exclude-members: ask_delay, ask_for_values, ask 104 | :undoc-members: 105 | 106 | .. autoclass:: pyvisa.resources.PXIInstrument 107 | :members: 108 | :inherited-members: 109 | :exclude-members: ask_delay, ask_for_values, ask 110 | :undoc-members: 111 | 112 | .. autoclass:: pyvisa.resources.PXIMemory 113 | :members: 114 | :inherited-members: 115 | :exclude-members: ask_delay, ask_for_values, ask 116 | :undoc-members: 117 | 118 | .. autoclass:: pyvisa.resources.VXIInstrument 119 | :members: 120 | :inherited-members: 121 | :exclude-members: ask_delay, ask_for_values, ask 122 | :undoc-members: 123 | 124 | .. autoclass:: pyvisa.resources.VXIMemory 125 | :members: 126 | :inherited-members: 127 | :exclude-members: ask_delay, ask_for_values, ask 128 | :undoc-members: 129 | 130 | .. autoclass:: pyvisa.resources.VXIBackplane 131 | :members: 132 | :inherited-members: 133 | :exclude-members: ask_delay, ask_for_values, ask 134 | :undoc-members: 135 | 136 | -------------------------------------------------------------------------------- /docs/api/visalibrarybase.rst: -------------------------------------------------------------------------------- 1 | .. _api_visalibrarybase: 2 | 3 | 4 | Visa Library 5 | ------------ 6 | 7 | .. autoclass:: pyvisa.highlevel.VisaLibraryBase 8 | :members: 9 | 10 | -------------------------------------------------------------------------------- /docs/architecture.rst: -------------------------------------------------------------------------------- 1 | .. _architecture: 2 | 3 | Architecture 4 | ============ 5 | 6 | PyVISA implements convenient and Pythonic programming in three layers: 7 | 8 | 1. Low-level: A wrapper around the shared visa library. 9 | 10 | The wrapper defines the argument types and response types of each function, 11 | as well as the conversions between Python objects and foreign types. 12 | 13 | You will normally not need to access these functions directly. If you do, 14 | it probably means that we need to improve layer 2. 15 | 16 | All level 1 functions are **static methods** of 17 | :class:`pyvisa.highlevel.VisaLibrary`. 18 | 19 | .. warning:: 20 | 21 | Notice however that low-level functions might not be present in all 22 | backends. For broader compatibility, do no use this layer. All the 23 | functionality should is available via the next layer. 24 | 25 | 26 | 2. Middle-level: A wrapping Python function for each function of the shared 27 | visa library. 28 | 29 | These functions call the low-level functions, adding some code to deal with 30 | type conversions for functions that return values by reference. 31 | These functions also have comprehensive and Python friendly documentation. 32 | 33 | You only need to access this layer if you want to control certain specific 34 | aspects of the VISA library which are not implemented by the corresponding 35 | resource class. 36 | 37 | All level 2 functions are **bound methods** of 38 | :class:`pyvisa.highlevel.VisaLibrary`. 39 | 40 | 3. High-level: An object-oriented layer for 41 | :class:`pyvisa.highlevel.ResourceManager` and 42 | :class:`pyvisa.resources.Resource` 43 | 44 | The ``ResourceManager`` implements methods to inspect connected resources. 45 | You also use this object to open other resources instantiating the 46 | appropriate ``Resource`` derived classes. 47 | 48 | ``Resource`` and the derived classes implement functions and attributes 49 | access to the underlying resources in a Pythonic way. 50 | 51 | Most of the time you will only need to instantiate a ``ResourceManager``. For a 52 | given resource, you will use the 53 | :meth:`pyvisa.highlevel.ResourceManager.open_resource` method to obtain the 54 | appropriate object. If needed, you will be able to access the ``VisaLibrary`` 55 | object directly using the :attr:`pyvisa.highlevel.ResourceManager.visalib` 56 | attribute. 57 | 58 | The ``VisaLibrary`` does the low-level calls. In the default NI Backend, 59 | levels 1 and 2 are implemented in the same package called 60 | :mod:`pyvisa.ctwrapper` (which stands for ctypes wrapper). This package is 61 | included in PyVISA. 62 | 63 | Other backends can be used just by passing the name of the backend to 64 | ``ResourceManager`` after the `@` symbol. See more information in 65 | :ref:`backends`. 66 | 67 | 68 | Calling middle- and low-level functions 69 | --------------------------------------- 70 | 71 | After you have instantiated the ``ResourceManager``:: 72 | 73 | >>> import visa 74 | >>> rm = visa.ResourceManager() 75 | 76 | you can access the corresponding ``VisaLibrary`` instance under the ``visalib`` 77 | attribute. 78 | 79 | As an example, consider the VISA function ``viMapAddress``. It appears in the 80 | low-level layer as the static method ``viMapAddress`` of ``visalib`` attributed 81 | and also appears in the middle-level layer as ``map_address``. 82 | 83 | You can recognize low and middle-level functions by their names. Low-level 84 | functions carry the same name as in the shared library, and they are prefixed 85 | by **vi**. Middle-level functions have a friendlier, more pythonic but still 86 | recognizable name. Typically, camelCase names where stripped from the leading 87 | **vi** and changed to underscore separated lower case names. The docs about 88 | these methods is located here :ref:`api`. 89 | 90 | 91 | Low-level 92 | ~~~~~~~~~ 93 | 94 | You can access the low-level functions directly exposed as static methods, 95 | for example:: 96 | 97 | >>> rm.visalib.viMapAddress() 98 | 99 | To call this functions you need to know the function declaration and how to 100 | interface it to python. To help you out, the ``VisaLibrary`` object also 101 | contains middle-level functions. 102 | 103 | It is very likely that you will need to access the VISA constants using these 104 | methods. You can find the information about these constants here 105 | :ref:`api_constants` 106 | 107 | 108 | Middle-level 109 | ~~~~~~~~~~~~ 110 | 111 | The ``VisaLibrary`` object exposes the middle-level functions which are 112 | one-to-one mapped from the foreign library as bound methods. 113 | 114 | Each middle-level function wraps one low-level function. 115 | In this case:: 116 | 117 | >>> rm.visalib.map_address() 118 | 119 | The calling convention and types are handled by the wrapper. 120 | 121 | -------------------------------------------------------------------------------- /docs/backends.rst: -------------------------------------------------------------------------------- 1 | .. _backends: 2 | 3 | 4 | A frontend for multiple backends 5 | ================================ 6 | 7 | A small historical note might help to make this section clearer. So bear with 8 | with me for a couple of lines. Originally PyVISA was a Python wrapper to the 9 | VISA library. More specifically, it was :py:mod:`ctypes` wrapper around the 10 | NI-VISA. This approach worked fine but made it difficult to develop other ways 11 | to communicate with instruments in platforms where NI-VISA was not available. 12 | Users had to change their programs to use other packages with different API. 13 | 14 | Since 1.6, PyVISA is a frontend to VISA. It provides a nice, Pythonic API and 15 | can connect to multiple backends. Each backend exposes a class derived from 16 | VisaLibraryBase that implements the low-level communication. The ctypes wrapper 17 | around NI-VISA is the default backend (called **ni**) and is bundled with 18 | PyVISA for simplicity. 19 | 20 | You can specify the backend to use when you instantiate the resource manager 21 | using the ``@`` symbol. Remembering that **ni** is the default, this:: 22 | 23 | >>> import visa 24 | >>> rm = visa.ResourceManager() 25 | 26 | is the same as this:: 27 | 28 | >>> import visa 29 | >>> rm = visa.ResourceManager('@ni') 30 | 31 | You can still provide the path to the library if needed:: 32 | 33 | >>> import visa 34 | >>> rm = visa.ResourceManager('/path/to/lib@ni') 35 | 36 | Under the hood, the :class:`pyvisa.highlevel.ResourceManager` looks for the 37 | requested backend and instantiate the VISA library that it provides. 38 | 39 | PyVISA locates backends by name. If you do: 40 | 41 | >>> import visa 42 | >>> rm = visa.ResourceManager('@somename') 43 | 44 | PyVISA will try to import a package/module named ``pyvisa-somename`` which 45 | should be installed in your system. This is a loosly coupled configuration free 46 | method. PyVISA does not need to know about any backend out there until you 47 | actually try to use it. 48 | 49 | You can list the installed backends by running the following code in the 50 | command line:: 51 | 52 | python -m visa info 53 | 54 | 55 | Developing a new Backend 56 | ------------------------ 57 | 58 | What does a minimum backend looks like? Quite simple:: 59 | 60 | from pyvisa.highlevel import VisaLibraryBase 61 | 62 | class MyLibrary(VisaLibraryBase): 63 | pass 64 | 65 | WRAPPER_CLASS = MyLibrary 66 | 67 | Additionally you can provide a staticmethod named get_debug_info` that should 68 | return a dictionary of debug information which is printed when you call 69 | ``python -m visa info`` or ``pyvisa-info`` 70 | 71 | .. note:: 72 | 73 | Your backend name should not end by ``-script`` or it will be discarded. 74 | This is because any script generated by setuptools containing the name 75 | pyvisa will be named ``pyvisa-*-script`` and they are obviously not backends. 76 | Examples are the ``pyvisa-shell`` and ``pyvisa-info`` scripts. 77 | 78 | An important aspect of developing a backend is knowing which VisaLibraryBase 79 | method to implement and what API to expose. 80 | 81 | A **complete** implementation of a VISA Library requires a lot of functions 82 | (basically almost all level 2 functions as described in :ref:`architecture` 83 | (there is also a complete list at the bottom of this page). But a working 84 | implementation does not require all of them. 85 | 86 | As a **very minimum** set you need: 87 | 88 | - **open_default_resource_manager**: returns a session to the Default 89 | Resource Manager resource. 90 | - **open**: Opens a session to the specified resource. 91 | - **close**: Closes the specified session, event, or find list. 92 | - **list_resources**: Returns a tuple of all connected devices matching 93 | query. 94 | 95 | (you can get the signature below or here :ref:`api_visalibrarybase`) 96 | 97 | But of course you cannot do anything interesting with just this. In general you 98 | will also need: 99 | 100 | - **get_attribute**: Retrieves the state of an attribute. 101 | - **set_atribute**: Sets the state of an attribute. 102 | 103 | If you need to start sending bytes to MessageBased instruments you will require: 104 | 105 | - **read**: Reads data from device or interface synchronously. 106 | - **write**: Writes data to device or interface synchronously. 107 | 108 | For other usages or devices, you might need to implement other functions. Is 109 | really up to you and your needs. 110 | 111 | These functions should raise a :class:`pyvisa.errors.VisaIOError` or emit a 112 | :class:`pyvisa.errors.VisaIOWarning` if necessary. 113 | 114 | 115 | Complete list of level 2 functions to implement:: 116 | 117 | def read_memory(self, session, space, offset, width, extended=False): 118 | def write_memory(self, session, space, offset, data, width, extended=False): 119 | def move_in(self, session, space, offset, length, width, extended=False): 120 | def move_out(self, session, space, offset, length, data, width, extended=False): 121 | def peek(self, session, address, width): 122 | def poke(self, session, address, width, data): 123 | def assert_interrupt_signal(self, session, mode, status_id): 124 | def assert_trigger(self, session, protocol): 125 | def assert_utility_signal(self, session, line): 126 | def buffer_read(self, session, count): 127 | def buffer_write(self, session, data): 128 | def clear(self, session): 129 | def close(self, session): 130 | def disable_event(self, session, event_type, mechanism): 131 | def discard_events(self, session, event_type, mechanism): 132 | def enable_event(self, session, event_type, mechanism, context=None): 133 | def flush(self, session, mask): 134 | def get_attribute(self, session, attribute): 135 | def gpib_command(self, session, data): 136 | def gpib_control_atn(self, session, mode): 137 | def gpib_control_ren(self, session, mode): 138 | def gpib_pass_control(self, session, primary_address, secondary_address): 139 | def gpib_send_ifc(self, session): 140 | def in_8(self, session, space, offset, extended=False): 141 | def in_16(self, session, space, offset, extended=False): 142 | def in_32(self, session, space, offset, extended=False): 143 | def in_64(self, session, space, offset, extended=False): 144 | def install_handler(self, session, event_type, handler, user_handle): 145 | def list_resources(self, session, query='?*::INSTR'): 146 | def lock(self, session, lock_type, timeout, requested_key=None): 147 | def map_address(self, session, map_space, map_base, map_size, 148 | def map_trigger(self, session, trigger_source, trigger_destination, mode): 149 | def memory_allocation(self, session, size, extended=False): 150 | def memory_free(self, session, offset, extended=False): 151 | def move(self, session, source_space, source_offset, source_width, destination_space, 152 | def move_asynchronously(self, session, source_space, source_offset, source_width, 153 | def move_in_8(self, session, space, offset, length, extended=False): 154 | def move_in_16(self, session, space, offset, length, extended=False): 155 | def move_in_32(self, session, space, offset, length, extended=False): 156 | def move_in_64(self, session, space, offset, length, extended=False): 157 | def move_out_8(self, session, space, offset, length, data, extended=False): 158 | def move_out_16(self, session, space, offset, length, data, extended=False): 159 | def move_out_32(self, session, space, offset, length, data, extended=False): 160 | def move_out_64(self, session, space, offset, length, data, extended=False): 161 | def open(self, session, resource_name, 162 | def open_default_resource_manager(self): 163 | def out_8(self, session, space, offset, data, extended=False): 164 | def out_16(self, session, space, offset, data, extended=False): 165 | def out_32(self, session, space, offset, data, extended=False): 166 | def out_64(self, session, space, offset, data, extended=False): 167 | def parse_resource(self, session, resource_name): 168 | def parse_resource_extended(self, session, resource_name): 169 | def peek_8(self, session, address): 170 | def peek_16(self, session, address): 171 | def peek_32(self, session, address): 172 | def peek_64(self, session, address): 173 | def poke_8(self, session, address, data): 174 | def poke_16(self, session, address, data): 175 | def poke_32(self, session, address, data): 176 | def poke_64(self, session, address, data): 177 | def read(self, session, count): 178 | def read_asynchronously(self, session, count): 179 | def read_stb(self, session): 180 | def read_to_file(self, session, filename, count): 181 | def set_attribute(self, session, attribute, attribute_state): 182 | def set_buffer(self, session, mask, size): 183 | def status_description(self, session, status): 184 | def terminate(self, session, degree, job_id): 185 | def uninstall_handler(self, session, event_type, handler, user_handle=None): 186 | def unlock(self, session): 187 | def unmap_address(self, session): 188 | def unmap_trigger(self, session, trigger_source, trigger_destination): 189 | def usb_control_in(self, session, request_type_bitmap_field, request_id, request_value, 190 | def usb_control_out(self, session, request_type_bitmap_field, request_id, request_value, 191 | def vxi_command_query(self, session, mode, command): 192 | def wait_on_event(self, session, in_event_type, timeout): 193 | def write(self, session, data): 194 | def write_asynchronously(self, session, data): 195 | def write_from_file(self, session, filename, count): 196 | 197 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # PyVISA documentation build configuration file 4 | # 5 | # This file is execfile()d with the current directory set to its containing dir. 6 | # 7 | # Note that not all possible configuration values are present in this 8 | # autogenerated file. 9 | # 10 | # All configuration values have a default; values that are commented out 11 | # serve to show the default. 12 | 13 | import os 14 | import pkg_resources 15 | import datetime 16 | 17 | 18 | # If extensions (or modules to document with autodoc) are in another directory, 19 | # add these directories to sys.path here. If the directory is relative to the 20 | # documentation root, use os.path.abspath to make it absolute, like shown here. 21 | #sys.path.insert(0, os.path.abspath('.')) 22 | 23 | # -- General configuration ----------------------------------------------------- 24 | 25 | # If your documentation needs a minimal Sphinx version, state it here. 26 | #needs_sphinx = '1.0' 27 | 28 | # Add any Sphinx extension module names here, as strings. They can be extensions 29 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 30 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.coverage', 'sphinx.ext.viewcode', 'sphinx.ext.mathjax'] 31 | 32 | # Add any paths that contain templates here, relative to this directory. 33 | templates_path = ['_templates'] 34 | 35 | # The suffix of source filenames. 36 | source_suffix = '.rst' 37 | 38 | # The encoding of source files. 39 | #source_encoding = 'utf-8-sig' 40 | 41 | # The master toctree document. 42 | master_doc = 'index' 43 | 44 | # General information about the project. 45 | project = 'PyVISA' 46 | author = 'PyVISA Authors' 47 | 48 | # The version info for the project you're documenting, acts as replacement for 49 | # |version| and |release|, also used in various other places throughout the 50 | # built documents. 51 | version = pkg_resources.get_distribution(project).version 52 | release = version 53 | this_year = datetime.date.today().year 54 | copyright = '%s, %s' % (this_year, author) 55 | 56 | # The language for content autogenerated by Sphinx. Refer to documentation 57 | # for a list of supported languages. 58 | #language = None 59 | 60 | # There are two options for replacing |today|: either, you set today to some 61 | # non-false value, then it is used: 62 | #today = '' 63 | # Else, today_fmt is used as the format for a strftime call. 64 | #today_fmt = '%B %d, %Y' 65 | 66 | # List of patterns, relative to source directory, that match files and 67 | # directories to ignore when looking for source files. 68 | exclude_patterns = ['_build'] 69 | 70 | # The reST default role (used for this markup: `text`) to use for all documents. 71 | #default_role = None 72 | 73 | # If true, '()' will be appended to :func: etc. cross-reference text. 74 | #add_function_parentheses = True 75 | 76 | # If true, the current module name will be prepended to all description 77 | # unit titles (such as .. function::). 78 | #add_module_names = True 79 | 80 | # If true, sectionauthor and moduleauthor directives will be shown in the 81 | # output. They are ignored by default. 82 | #show_authors = False 83 | 84 | # The name of the Pygments (syntax highlighting) style to use. 85 | pygments_style = 'sphinx' 86 | 87 | # A list of ignored prefixes for module index sorting. 88 | #modindex_common_prefix = [] 89 | 90 | 91 | # -- Options for HTML output --------------------------------------------------- 92 | 93 | # The theme to use for HTML and HTML Help pages. See the documentation for 94 | # a list of builtin themes. 95 | #html_theme = 'default' 96 | html_theme = "sphinx_rtd_theme" 97 | 98 | # Theme options are theme-specific and customize the look and feel of a theme 99 | # further. For a list of options available for each theme, see the 100 | # documentation. 101 | #html_theme_options = {} 102 | 103 | # Add any paths that contain custom themes here, relative to this directory. 104 | #html_theme_path = [] 105 | 106 | # The name for this set of Sphinx documents. If None, it defaults to 107 | # " v documentation". 108 | #html_title = None 109 | 110 | # A shorter title for the navigation bar. Default is the same as html_title. 111 | #html_short_title = None 112 | 113 | # The name of an image file (relative to this directory) to place at the top 114 | # of the sidebar. 115 | #html_logo = None 116 | 117 | # The name of an image file (within the static path) to use as favicon of the 118 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 119 | # pixels large. 120 | #html_favicon = None 121 | 122 | # Add any paths that contain custom static files (such as style sheets) here, 123 | # relative to this directory. They are copied after the builtin static files, 124 | # so a file named "default.css" will overwrite the builtin "default.css". 125 | html_static_path = ['_static'] 126 | 127 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 128 | # using the given strftime format. 129 | #html_last_updated_fmt = '%b %d, %Y' 130 | 131 | # If true, SmartyPants will be used to convert quotes and dashes to 132 | # typographically correct entities. 133 | #html_use_smartypants = True 134 | 135 | # Custom sidebar templates, maps document names to template names. 136 | #html_sidebars = {} 137 | 138 | # Additional templates that should be rendered to pages, maps page names to 139 | # template names. 140 | #html_additional_pages = {} 141 | 142 | # If false, no module index is generated. 143 | #html_domain_indices = True 144 | 145 | # If false, no index is generated. 146 | #html_use_index = True 147 | 148 | # If true, the index is split into individual pages for each letter. 149 | #html_split_index = False 150 | 151 | # If true, links to the reST sources are added to the pages. 152 | #html_show_sourcelink = True 153 | 154 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 155 | #html_show_sphinx = True 156 | 157 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 158 | #html_show_copyright = True 159 | 160 | # If true, an OpenSearch description file will be output, and all pages will 161 | # contain a tag referring to it. The value of this option must be the 162 | # base URL from which the finished HTML is served. 163 | #html_use_opensearch = '' 164 | 165 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 166 | #html_file_suffix = None 167 | 168 | # Output file base name for HTML help builder. 169 | htmlhelp_basename = 'pyvisatdoc' 170 | 171 | 172 | # -- Options for LaTeX output -------------------------------------------------- 173 | 174 | latex_elements = { 175 | # The paper size ('letterpaper' or 'a4paper'). 176 | #'papersize': 'letterpaper', 177 | 178 | # The font size ('10pt', '11pt' or '12pt'). 179 | #'pointsize': '10pt', 180 | 181 | # Additional stuff for the LaTeX preamble. 182 | #'preamble': '', 183 | } 184 | 185 | # Grouping the document tree into LaTeX files. List of tuples 186 | # (source start file, target name, title, author, documentclass [howto/manual]). 187 | latex_documents = [ 188 | ('index', 'pyvisa.tex', 'PyVISA Documentation', 189 | 'PyVISA Authors', 'manual'), 190 | ] 191 | 192 | # The name of an image file (relative to this directory) to place at the top of 193 | # the title page. 194 | #latex_logo = None 195 | 196 | # For "manual" documents, if this is true, then toplevel headings are parts, 197 | # not chapters. 198 | #latex_use_parts = False 199 | 200 | # If true, show page references after internal links. 201 | #latex_show_pagerefs = False 202 | 203 | # If true, show URL addresses after external links. 204 | #latex_show_urls = False 205 | 206 | # Documents to append as an appendix to all manuals. 207 | #latex_appendices = [] 208 | 209 | # If false, no module index is generated. 210 | #latex_domain_indices = True 211 | 212 | 213 | # -- Options for manual page output -------------------------------------------- 214 | 215 | # One entry per manual page. List of tuples 216 | # (source start file, name, description, authors, manual section). 217 | man_pages = [ 218 | ('index', 'pyvisa', 'PyVISA Documentation', 219 | ['PyVISA Authors'], 1) 220 | ] 221 | 222 | # If true, show URL addresses after external links. 223 | #man_show_urls = False 224 | 225 | 226 | # -- Options for Texinfo output ------------------------------------------------ 227 | 228 | # Grouping the document tree into Texinfo files. List of tuples 229 | # (source start file, target name, title, author, 230 | # dir menu entry, description, category) 231 | texinfo_documents = [ 232 | ('index', 'PyVISA', 'PyVISA Documentation', 233 | 'PyVISA Authors', 'PyVISA', 'One line description of project.', 234 | 'Miscellaneous'), 235 | ] 236 | 237 | # Documents to append as an appendix to all manuals. 238 | #texinfo_appendices = [] 239 | 240 | # If false, no module index is generated. 241 | #texinfo_domain_indices = True 242 | 243 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 244 | #texinfo_show_urls = 'footnote' 245 | 246 | 247 | # -- Options for Epub output --------------------------------------------------- 248 | 249 | # Bibliographic Dublin Core info. 250 | epub_title = project 251 | epub_author = author 252 | epub_publisher = author 253 | epub_copyright = copyright 254 | 255 | # The language of the text. It defaults to the language option 256 | # or en if the language is not set. 257 | #epub_language = '' 258 | 259 | # The scheme of the identifier. Typical schemes are ISBN or URL. 260 | #epub_scheme = '' 261 | 262 | # The unique identifier of the text. This can be a ISBN number 263 | # or the project homepage. 264 | #epub_identifier = '' 265 | 266 | # A unique identification for the text. 267 | #epub_uid = '' 268 | 269 | # A tuple containing the cover image and cover page html template filenames. 270 | #epub_cover = () 271 | 272 | # HTML files that should be inserted before the pages created by sphinx. 273 | # The format is a list of tuples containing the path and title. 274 | #epub_pre_files = [] 275 | 276 | # HTML files shat should be inserted after the pages created by sphinx. 277 | # The format is a list of tuples containing the path and title. 278 | #epub_post_files = [] 279 | 280 | # A list of files that should not be packed into the epub file. 281 | #epub_exclude_files = [] 282 | 283 | # The depth of the table of contents in toc.ncx. 284 | #epub_tocdepth = 3 285 | 286 | # Allow duplicate toc entries. 287 | #epub_tocdup = True 288 | 289 | 290 | # Example configuration for intersphinx: refer to the Python standard library. 291 | intersphinx_mapping = {'python': ('http://docs.python.org/3', None)} 292 | -------------------------------------------------------------------------------- /docs/configuring.rst: -------------------------------------------------------------------------------- 1 | .. _configuring: 2 | 3 | Configuring the backend 4 | ============================ 5 | 6 | Currently there are two backends available: The one included in pyvisa, which 7 | uses the NI library, and the backend provided by pyvisa-py, which is a pure python implementation of the VISA library. 8 | If no backend is specified, pyvisa uses the NI backend if the NI library has been installed (see next section for details). Failing that, it uses the pyvisa-py backend. 9 | 10 | You can also select a desired backend by passing a parameter to the ResourceManager, shown here for pyvisa-py: 11 | 12 | >>> visa.ResourceManager('@py') 13 | 14 | Alternatively it can also be selected by setting the environment variable 15 | PYVISA_LIBRARY. It takes the same values as the ResourceManager constructor. 16 | 17 | Configuring the NI backend 18 | ========================== 19 | 20 | .. note:: 21 | 22 | The NI backend requires that you install first the NI-VISA library. You can 23 | get info here: (:ref:`getting_nivisa`) 24 | 25 | 26 | In most cases PyVISA will be able to find the location of the shared visa 27 | library. If this does not work or you want to use another one, you need to 28 | provide the library path to the :class:`pyvisa.highlevel.ResourceManager` 29 | constructor:: 30 | 31 | >>> rm = ResourceManager('Path to library') 32 | 33 | 34 | You can make this library the default for all PyVISA applications by using 35 | a configuration file called :file:`.pyvisarc` (mind the leading dot) in your 36 | `home directory`_. 37 | 38 | ========================== ================================================== 39 | Operating System Location 40 | ========================== ================================================== 41 | Windows NT :file:`\\WINNT\\Profiles\\` 42 | -------------------------- -------------------------------------------------- 43 | Windows 2000, XP and 2003 :file:`\\Documents and Settings\\` 44 | -------------------------- -------------------------------------------------- 45 | Windows Vista, 7 or 8 :file:`\\Users\\` 46 | -------------------------- -------------------------------------------------- 47 | Mac OS X :file:`/Users/` 48 | -------------------------- -------------------------------------------------- 49 | Linux :file:`/home/` (depends on the distro) 50 | ========================== ================================================== 51 | 52 | For example in Windows XP, place it in your user folder "Documents and Settings" 53 | folder, e.g. :file:`C:\\Documents and Settings\\smith\\.pyvisarc` if "smith" is 54 | the name of your login account. 55 | 56 | This file has the format of an INI file. For example, if the library 57 | is at :file:`/usr/lib/libvisa.so.7`, the file :file:`.pyvisarc` must 58 | contain the following:: 59 | 60 | [Paths] 61 | 62 | VISA library: /usr/lib/libvisa.so.7 63 | 64 | Please note that `[Paths]` is treated case-sensitively. 65 | 66 | You can define a site-wide configuration file at 67 | :file:`/usr/share/pyvisa/.pyvisarc` (It may also be 68 | :file:`/usr/local/...` depending on the location of your Python). 69 | Under Windows, this file is usually placed at 70 | :file:`c:\\Python27\\share\\pyvisa\\.pyvisarc`. 71 | 72 | If you encounter any problem, take a look at the :ref:`faq`. There you will 73 | find the solutions to common problem as well as useful debugging techniques. If 74 | everything fails, feel free to open an issue in our `issue tracker`_ 75 | 76 | .. _`home directory`: http://en.wikipedia.org/wiki/Home_directory 77 | .. _`issue tracker`: https://github.com/pyvisa/pyvisa/issues 78 | -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | .. _contributing: 2 | 3 | Contributing to PyVISA 4 | ====================== 5 | 6 | You can contribute in different ways: 7 | 8 | Report issues 9 | ------------- 10 | 11 | You can report any issues with the package, the documentation to the PyVISA `issue tracker`_. Also feel free to submit feature requests, comments or questions. In some cases, platform specific information is required. If you think this is the case, run the following command and paste the output into the issue:: 12 | 13 | python -m visa info 14 | 15 | It is useful that you also provide the log output. To obtain it, add the following lines to your code:: 16 | 17 | import visa 18 | visa.log_to_screen() 19 | 20 | 21 | Contribute code 22 | --------------- 23 | 24 | To contribute fixes, code or documentation to PyVISA, send us a patch, or fork PyVISA in github_ and submit the changes using a pull request. 25 | 26 | You can also get the code from PyPI_ or GitHub_. You can either clone the public repository:: 27 | 28 | $ git clone git://github.com/pyvisa/pyvisa.git 29 | 30 | Download the tarball:: 31 | 32 | $ curl -OL https://github.com/pyvisa/pyvisa/tarball/master 33 | 34 | Or, download the zipball:: 35 | 36 | $ curl -OL https://github.com/pyvisa/pyvisa/zipball/master 37 | 38 | Once you have a copy of the source, you can embed it in your Python package, or install it into your site-packages easily:: 39 | 40 | $ python setup.py install 41 | 42 | 43 | .. note:: If you have an old system installation of Python and you don't want to 44 | mess with it, you can try `Anaconda CE`_. It is a free Python distribution by 45 | Continuum Analytics that includes many scientific packages. 46 | 47 | 48 | Contributing to an existing backend 49 | ----------------------------------- 50 | 51 | Backends are the central piece of PyVISA as they provide the low level communication 52 | over the different interfaces. There a couple of backends in the wild which can use 53 | your help. Look them up in PyPI_ (try `pyvisa``` in the search box) and see where you 54 | can help. 55 | 56 | 57 | Contributing a new backend 58 | -------------------------- 59 | 60 | If you think there is a new way that low level communication can be achieved, go for 61 | it. You can use any of the existing backends as a template or start a thread in the 62 | `issue tracker`_ and we will be happy to help you. 63 | 64 | 65 | 66 | 67 | .. _easy_install: http://pypi.python.org/pypi/setuptools 68 | .. _Python: http://www.python.org/ 69 | .. _pip: http://www.pip-installer.org/ 70 | .. _`Anaconda CE`: https://store.continuum.io/cshop/anaconda 71 | .. _PyPI: https://pypi.python.org/pypi/PyVISA 72 | .. _`National Instruments's VISA`: http://ni.com/visa/ 73 | .. _github: http://github.com/pyvisa/pyvisa 74 | .. _`issue tracker`: https://github.com/pyvisa/pyvisa/issues 75 | 76 | 77 | -------------------------------------------------------------------------------- /docs/default.css: -------------------------------------------------------------------------------- 1 | /* 2 | :Author: David Goodger 3 | :Contact: goodger@users.sourceforge.net 4 | :Date: $Date$ 5 | :Version: $Revision$ 6 | :Copyright: This stylesheet has been placed in the public domain. 7 | 8 | Default cascading style sheet for the HTML output of Docutils. 9 | */ 10 | 11 | /* "! important" is used here to override other ``margin-top`` and 12 | ``margin-bottom`` styles that are later in the stylesheet or 13 | more specific. See http://www.w3.org/TR/CSS1#the-cascade */ 14 | .first { 15 | margin-top: 0 ! important } 16 | 17 | .last { 18 | margin-bottom: 0 ! important } 19 | 20 | .hidden { 21 | display: none } 22 | 23 | a.toc-backref { 24 | text-decoration: none ; 25 | color: black } 26 | 27 | blockquote.epigraph { 28 | margin: 2em 5em ; } 29 | 30 | dl.docutils dd { 31 | margin-bottom: 0.5em } 32 | 33 | /* Uncomment (and remove this text!) to get bold-faced definition list terms 34 | dl.docutils dt { 35 | font-weight: bold } 36 | */ 37 | 38 | div.abstract { 39 | margin: 2em 5em } 40 | 41 | div.abstract p.topic-title { 42 | font-weight: bold ; 43 | text-align: center } 44 | 45 | div.admonition, div.attention, div.caution, div.danger, div.error, 46 | div.hint, div.important, div.note, div.tip, div.warning { 47 | margin: 2em ; 48 | border: medium outset ; 49 | padding: 1em } 50 | 51 | div.admonition p.admonition-title, div.hint p.admonition-title, 52 | div.important p.admonition-title, div.note p.admonition-title, 53 | div.tip p.admonition-title { 54 | font-weight: bold ; 55 | font-family: sans-serif } 56 | 57 | div.attention p.admonition-title, div.caution p.admonition-title, 58 | div.danger p.admonition-title, div.error p.admonition-title, 59 | div.warning p.admonition-title { 60 | color: red ; 61 | font-weight: bold ; 62 | font-family: sans-serif } 63 | 64 | /* Uncomment (and remove this text!) to get reduced vertical space in 65 | compound paragraphs. 66 | div.compound .compound-first, div.compound .compound-middle { 67 | margin-bottom: 0.5em } 68 | 69 | div.compound .compound-last, div.compound .compound-middle { 70 | margin-top: 0.5em } 71 | */ 72 | 73 | div.dedication { 74 | margin: 2em 5em ; 75 | text-align: center ; 76 | font-style: italic } 77 | 78 | div.dedication p.topic-title { 79 | font-weight: bold ; 80 | font-style: normal } 81 | 82 | div.figure { 83 | margin-left: 2em } 84 | 85 | div.footer, div.header { 86 | font-size: smaller } 87 | 88 | div.line-block { 89 | display: block ; 90 | margin-top: 1em ; 91 | margin-bottom: 1em } 92 | 93 | div.line-block div.line-block { 94 | margin-top: 0 ; 95 | margin-bottom: 0 ; 96 | margin-left: 1.5em } 97 | 98 | div.sidebar { 99 | margin-left: 1em ; 100 | border: medium outset ; 101 | padding: 1em ; 102 | background-color: #ffffee ; 103 | width: 40% ; 104 | float: right ; 105 | clear: right } 106 | 107 | div.sidebar p.rubric { 108 | font-family: sans-serif ; 109 | font-size: medium } 110 | 111 | div.system-messages { 112 | margin: 5em } 113 | 114 | div.system-messages h1 { 115 | color: red } 116 | 117 | div.system-message { 118 | border: medium outset ; 119 | padding: 1em } 120 | 121 | div.system-message p.system-message-title { 122 | color: red ; 123 | font-weight: bold } 124 | 125 | div.topic { 126 | margin: 2em } 127 | 128 | h1.title { 129 | text-align: center } 130 | 131 | h2.subtitle { 132 | text-align: center } 133 | 134 | hr.docutils { 135 | width: 75% } 136 | 137 | ol.simple, ul.simple { 138 | margin-bottom: 1em } 139 | 140 | ol.arabic { 141 | list-style: decimal } 142 | 143 | ol.loweralpha { 144 | list-style: lower-alpha } 145 | 146 | ol.upperalpha { 147 | list-style: upper-alpha } 148 | 149 | ol.lowerroman { 150 | list-style: lower-roman } 151 | 152 | ol.upperroman { 153 | list-style: upper-roman } 154 | 155 | p.attribution { 156 | text-align: right ; 157 | margin-left: 50% } 158 | 159 | p.caption { 160 | font-style: italic } 161 | 162 | p.credits { 163 | font-style: italic ; 164 | font-size: smaller } 165 | 166 | p.label { 167 | white-space: nowrap } 168 | 169 | p.rubric { 170 | font-weight: bold ; 171 | font-size: larger ; 172 | color: maroon ; 173 | text-align: center } 174 | 175 | p.sidebar-title { 176 | font-family: sans-serif ; 177 | font-weight: bold ; 178 | font-size: larger } 179 | 180 | p.sidebar-subtitle { 181 | font-family: sans-serif ; 182 | font-weight: bold } 183 | 184 | p.topic-title { 185 | font-weight: bold } 186 | 187 | pre.address { 188 | margin-bottom: 0 ; 189 | margin-top: 0 ; 190 | font-family: serif ; 191 | font-size: 100% } 192 | 193 | pre.line-block { 194 | font-family: serif ; 195 | font-size: 100% } 196 | 197 | pre.literal-block, pre.doctest-block { 198 | margin-left: 2em ; 199 | margin-right: 2em ; 200 | background-color: #eeeeee } 201 | 202 | span.classifier { 203 | font-family: sans-serif ; 204 | font-style: oblique } 205 | 206 | span.classifier-delimiter { 207 | font-family: sans-serif ; 208 | font-weight: bold } 209 | 210 | span.interpreted { 211 | font-family: sans-serif } 212 | 213 | span.option { 214 | white-space: nowrap } 215 | 216 | span.pre { 217 | white-space: pre } 218 | 219 | span.problematic { 220 | color: red } 221 | 222 | table.citation { 223 | border-left: solid thin gray } 224 | 225 | table.docinfo { 226 | margin: 2em 4em } 227 | 228 | table.docutils { 229 | margin-top: 0.5em ; 230 | margin-bottom: 0.5em } 231 | 232 | table.footnote { 233 | border-left: solid thin black } 234 | 235 | table.docutils td, table.docutils th, 236 | table.docinfo td, table.docinfo th { 237 | padding-left: 0.5em ; 238 | padding-right: 0.5em ; 239 | vertical-align: top } 240 | 241 | table.docutils th.field-name, table.docinfo th.docinfo-name { 242 | font-weight: bold ; 243 | text-align: left ; 244 | white-space: nowrap ; 245 | padding-left: 0 } 246 | 247 | h1 tt.docutils, h2 tt.docutils, h3 tt.docutils, 248 | h4 tt.docutils, h5 tt.docutils, h6 tt.docutils { 249 | font-size: 100% } 250 | 251 | tt.docutils { 252 | background-color: #eeeeee } 253 | 254 | ul.auto-toc { 255 | list-style-type: none } 256 | -------------------------------------------------------------------------------- /docs/example.rst: -------------------------------------------------------------------------------- 1 | 2 | 3 | .. _sec:more-complex-example: 4 | 5 | A more complex example 6 | ====================== 7 | 8 | The following example shows how to use SCPI commands with a Keithley 9 | 2000 multimeter in order to measure 10 voltages. After having read 10 | them, the program calculates the average voltage and prints it on the 11 | screen. 12 | 13 | I'll explain the program step-by-step. First, we have to initialise 14 | the instrument:: 15 | 16 | >>> keithley = rm.open_resource("GPIB::12") 17 | >>> keithley.write("*rst; status:preset; *cls") 18 | 19 | Here, we create the instrument variable *keithley*, which is used for 20 | all further operations on the instrument. Immediately after it, we 21 | send the initialisation and reset message to the instrument. 22 | 23 | The next step is to write all the measurement parameters, in 24 | particular the interval time (500ms) and the number of readings (10) 25 | to the instrument. I won't explain it in detail. Have a look at an 26 | SCPI and/or Keithley 2000 manual. 27 | 28 | .. code-block:: python 29 | 30 | >>> interval_in_ms = 500 31 | >>> number_of_readings = 10 32 | >>> keithley.write("status:measurement:enable 512; *sre 1") 33 | >>> keithley.write("sample:count %d" % number_of_readings) 34 | >>> keithley.write("trigger:source bus") 35 | >>> keithley.write("trigger:delay %f" % (interval_in_ms / 1000.0)) 36 | >>> keithley.write("trace:points %d" % number_of_readings) 37 | >>> keithley.write("trace:feed sense1; feed:control next") 38 | 39 | Okay, now the instrument is prepared to do the measurement. The next 40 | three lines make the instrument waiting for a trigger pulse, trigger 41 | it, and wait until it sends a "service request":: 42 | 43 | >>> keithley.write("initiate") 44 | >>> keithley.assert_trigger() 45 | >>> keithley.wait_for_srq() 46 | 47 | With sending the service request, the instrument tells us that the 48 | measurement has been finished and that the results are ready for 49 | transmission. We could read them with `keithley.query("trace:data?")` 50 | however, then we'd get: 51 | 52 | .. code-block:: none 53 | 54 | -000.0004E+0,-000.0005E+0,-000.0004E+0,-000.0007E+0, 55 | -000.0000E+0,-000.0007E+0,-000.0008E+0,-000.0004E+0, 56 | -000.0002E+0,-000.0005E+0 57 | 58 | which we would have to convert to a Python list of numbers. 59 | Fortunately, the `query_ascii_values()` method does this work for us:: 60 | 61 | >>> voltages = keithley.query_ascii_values("trace:data?") 62 | >>> print("Average voltage: ", sum(voltages) / len(voltages)) 63 | 64 | Finally, we should reset the instrument's data buffer and SRQ status 65 | register, so that it's ready for a new run. Again, this is explained 66 | in detail in the instrument's manual:: 67 | 68 | >>> keithley.query("status:measurement?") 69 | >>> keithley.write("trace:clear; feed:control next") 70 | 71 | That's it. 18 lines of lucid code. (Well, SCPI is awkward, but 72 | that's another story.) 73 | -------------------------------------------------------------------------------- /docs/faq.rst: -------------------------------------------------------------------------------- 1 | .. _faq: 2 | 3 | Frequently asked questions 4 | ========================== 5 | 6 | 7 | Is *PyVISA* endorsed by National Instruments? 8 | --------------------------------------------- 9 | 10 | No. *PyVISA* is developed independently of National Instrument as a wrapper 11 | for the VISA library. 12 | 13 | 14 | Who makes *PyVISA*? 15 | ------------------- 16 | 17 | PyVISA was originally programmed by Torsten Bronger and Gregor Thalhammer. 18 | It is based on earlier experiences by Thalhammer. 19 | 20 | It was maintained from March 2012 to August 2013 by Florian Bauer. 21 | It is currently maintained by Hernan E. Grecco . 22 | 23 | Take a look at AUTHORS_ for more information 24 | 25 | 26 | Is PyVISA thread-safe? 27 | ---------------------- 28 | 29 | Yes, PyVISA is thread safe starting from version 1.6. 30 | 31 | 32 | I have an error in my program and I am having trouble to fix it 33 | --------------------------------------------------------------- 34 | 35 | PyVISA provides useful logs of all operations. Add the following commands to 36 | your program and run it again:: 37 | 38 | import visa 39 | visa.log_to_screen() 40 | 41 | 42 | I found a bug, how can I report it? 43 | ----------------------------------- 44 | 45 | Please report it on the `Issue Tracker`_, including operating system, python 46 | version and library version. In addition you might add supporting information 47 | by pasting the output of this command:: 48 | 49 | python -m visa info 50 | 51 | 52 | Error: Image not found 53 | ---------------------- 54 | 55 | This error occurs when you have provided an invalid path for the VISA library. 56 | Check that the path provided to the constructor or in the configuration file 57 | 58 | 59 | Error: Could not found VISA library 60 | ----------------------------------- 61 | 62 | This error occurs when you have not provided a path for the VISA library and 63 | PyVISA is not able to find it for you. You can solve it by providing the 64 | library path to the ``VisaLibrary`` or ``ResourceManager`` constructor:: 65 | 66 | >>> visalib = VisaLibrary('/path/to/library') 67 | 68 | or:: 69 | 70 | >>> rm = ResourceManager('Path to library') 71 | 72 | or creating a configuration file as described in :ref:`configuring`. 73 | 74 | 75 | Error: No matching architecture 76 | ------------------------------- 77 | 78 | This error occurs when you the Python architecture does not match the VISA 79 | architecture. 80 | 81 | .. note:: PyVISA tries to parse the error from the underlying foreign function 82 | library to provide a more useful error message. If it does not succeed, it 83 | shows the original one. 84 | 85 | In Mac OS X the original error message looks like this:: 86 | 87 | OSError: dlopen(/Library/Frameworks/visa.framework/visa, 6): no suitable image found. Did find: 88 | /Library/Frameworks/visa.framework/visa: no matching architecture in universal wrapper 89 | /Library/Frameworks/visa.framework/visa: no matching architecture in universal wrapper 90 | 91 | In Linux the original error message looks like this:: 92 | 93 | OSError: Could not open VISA library: 94 | Error while accessing /usr/local/vxipnp/linux/bin/libvisa.so.7:/usr/local/vxipnp/linux/bin/libvisa.so.7: wrong ELF class: ELFCLASS32 95 | 96 | 97 | First, determine the details of your installation with the help of the 98 | following debug command:: 99 | 100 | python -m visa info 101 | 102 | You will see the 'bitness' of the Python interpreter and at the end you will 103 | see the list of VISA libraries that PyVISA was able to find. 104 | 105 | The solution is to: 106 | 107 | 1. Install and use a VISA library matching your Python 'bitness' 108 | 109 | Download and install it from **National Instruments's VISA**. Run the 110 | debug command again to see if the new library was found by PyVISA. If not, 111 | create a configuration file as described in :ref:`configuring`. 112 | 113 | If there is no VISA library with the correct bitness available, try 114 | solution 2. 115 | 116 | or 117 | 118 | 2. Install and use a Python matching your VISA library 'bitness' 119 | 120 | In Windows and Linux: Download and install Python with the matching 121 | bitness. Run your script again using the new Python 122 | 123 | In Mac OS X, Python is usually delivered as universal binary (32 and 124 | 64 bits). 125 | 126 | You can run it in 32 bit by running:: 127 | 128 | arch -i386 python myscript.py 129 | 130 | or in 64 bits by running:: 131 | 132 | arch -x86_64 python myscript.py 133 | 134 | You can create an alias by adding the following line 135 | 136 | alias python32="arch -i386 python" 137 | 138 | into your .bashrc or .profile or ~/.bash_profile (or whatever file 139 | depending on which shell you are using.) 140 | 141 | You can also create a `virtual environment`_ for this. 142 | 143 | 144 | Where can I get more information about VISA? 145 | -------------------------------------------- 146 | 147 | 148 | * The original VISA docs: 149 | 150 | - `VISA specification`_ (scroll down to the end) 151 | - `VISA library specification`_ 152 | - `VISA specification for textual languages`_ 153 | 154 | * The very good VISA manuals from `National Instruments's VISA`_: 155 | 156 | - `NI-VISA User Manual`_ 157 | - `NI-VISA Programmer Reference Manual`_ 158 | - `NI-VISA help file`_ in HTML 159 | 160 | .. _`VISA specification`: 161 | http://www.ivifoundation.org/Downloads/Specifications.htm 162 | .. _`VISA library specification`: 163 | http://www.ivifoundation.org/Downloads/Class%20Specifications/vpp43.doc 164 | .. _`VISA specification for textual languages`: 165 | http://www.ivifoundation.org/Downloads/Class%20Specifications/vpp432.doc 166 | .. _`National Instruments's VISA`: http://ni.com/visa/ 167 | .. _`NI-VISA Programmer Reference Manual`: 168 | http://digital.ni.com/manuals.nsf/websearch/87E52268CF9ACCEE86256D0F006E860D 169 | .. _`NI-VISA help file`: 170 | http://digital.ni.com/manuals.nsf/websearch/21992F3750B967ED86256F47007B00B3 171 | .. _`NI-VISA User Manual`: 172 | http://digital.ni.com/manuals.nsf/websearch/266526277DFF74F786256ADC0065C50C 173 | 174 | 175 | .. _`AUTHORS`: https://github.com/pyvisa/pyvisa/blob/master/AUTHORS 176 | .. _`Issue Tracker`: https://github.com/pyvisa/pyvisa/issues 177 | .. _`virtual environment`: http://www.virtualenv.org/en/latest/ 178 | -------------------------------------------------------------------------------- /docs/getting.rst: -------------------------------------------------------------------------------- 1 | .. _getting: 2 | 3 | Installation 4 | ============ 5 | 6 | PyVISA is a frontend to the VISA library. It runs on Python 2.7 and 3.4+. 7 | 8 | You can install it using pip_:: 9 | 10 | $ pip install -U pyvisa 11 | 12 | 13 | Backend 14 | ------- 15 | 16 | In order for PyVISA to work, you need to have a suitable backend. PyVISA 17 | includes a backend that wraps the `National Instruments's VISA`_ library. 18 | However, you need to download and install the library yourself 19 | (See :ref:`getting_nivisa`). There are multiple VISA implementations from 20 | different vendors. PyVISA is tested only against 21 | `National Instruments's VISA`_. 22 | 23 | .. warning:: 24 | 25 | PyVISA works with 32- and 64- bit Python and can deal with 32- and 64-bit 26 | VISA libraries without any extra configuration. What PyVISA cannot do is 27 | open a 32-bit VISA library while running in 64-bit Python (or the other 28 | way around). 29 | 30 | **You need to make sure that the Python and VISA library have the same bitness** 31 | 32 | Alternatively, you can install `PyVISA-Py`_ which is a pure Python 33 | implementation of the VISA standard. You can install it using pip_:: 34 | 35 | $ pip install -U pyvisa-py 36 | 37 | .. note:: 38 | 39 | At the moment, `PyVISA-Py` implements only a limited subset of the VISA 40 | standard and does not support all protocols on all bus systems. Please 41 | refer to its documentation for more details. 42 | 43 | 44 | Testing your installation 45 | ------------------------- 46 | 47 | 48 | That's all! You can check that PyVISA is correctly installed by starting up 49 | python, and creating a ResourceManager: 50 | 51 | >>> import visa 52 | >>> rm = visa.ResourceManager() 53 | >>> print(rm.list_resources()) 54 | 55 | If you encounter any problem, take a look at the :ref:`faq`. There you will 56 | find the solutions to common problem as well as useful debugging techniques. 57 | If everything fails, feel free to open an issue in our `issue tracker`_ 58 | 59 | 60 | Using the development version 61 | ----------------------------- 62 | 63 | You can install the latest development version (at your own risk) directly 64 | form GitHub_:: 65 | 66 | $ pip install -U https://github.com/pyvisa/pyvisa/zipball/master 67 | 68 | 69 | .. note:: 70 | 71 | If you have an old system installation of Python and you don't want to 72 | mess with it, you can try `Anaconda CE`_. It is a free Python distribution 73 | by Continuum Analytics that includes many scientific packages. 74 | 75 | 76 | .. _easy_install: http://pypi.python.org/pypi/setuptools 77 | .. _Python: http://www.python.org/ 78 | .. _pip: http://www.pip-installer.org/ 79 | .. _`Anaconda CE`: https://store.continuum.io/cshop/anaconda 80 | .. _PyPI: https://pypi.python.org/pypi/PyVISA 81 | .. _GitHub: https://github.com/pyvisa/pyvisa 82 | .. _`National Instruments's VISA`: http://ni.com/visa/ 83 | .. _`issue tracker`: https://github.com/pyvisa/pyvisa/issues 84 | .. _`PyVISA-Py`: http://pyvisa-py.readthedocs.io/en/latest/ 85 | -------------------------------------------------------------------------------- /docs/getting_nivisa.rst: -------------------------------------------------------------------------------- 1 | .. _getting_nivisa: 2 | 3 | NI-VISA Installation 4 | ==================== 5 | 6 | In every OS, the NI-VISA library bitness (i.e. 32- or 64-bit) has to match the 7 | Python bitness. So first you need to install a NI-VISA that works with your OS 8 | and then choose the Python version matching the installed NI-VISA bitness. 9 | 10 | PyVISA includes a debugging command to help you troubleshoot this 11 | (and other things):: 12 | 13 | python -m visa info 14 | 15 | or equivalently:: 16 | 17 | pyvisa-info 18 | 19 | According to National Instruments, NI VISA **17.5** is available for the 20 | following platforms. 21 | 22 | .. note:: 23 | 24 | If NI-VISA is not available for your system, take a look at the :ref:`faq`. 25 | 26 | 27 | Mac OS X 28 | -------- 29 | 30 | Download `NI-VISA for Mac OS X`_ 31 | 32 | Supports: 33 | 34 | - Mac OS X 10.7.x x86 and x86-64 35 | - Mac OS X 10.8.x 36 | 37 | *64-bit VISA applications are supported for a limited set of instrumentation 38 | buses. The supported buses are ENET-Serial, USB, and TCPIP. Logging VISA 39 | operations in NI I/O Trace from 64-bit VISA applications is not supported.* 40 | 41 | Windows 42 | ------- 43 | 44 | Download `NI-VISA for Windows`_ 45 | 46 | Suports: 47 | 48 | - Windows Server 2003 R2 (32-bit version only) 49 | - Windows Server 2008 R2 (64-bit version only) 50 | - Windows 8 x64 Edition (64-bit version) 51 | - Windows 8 (32-bit version) 52 | - Windows 7 x64 Edition (64-bit version) 53 | - Windows 7 (32-bit version) 54 | - Windows Vista x64 Edition (64-bit version) 55 | - Windows Vista (32-bit version) 56 | - Windows XP Service Pack 3 57 | 58 | *Support for Windows Server 2003 R2 may require disabling physical address 59 | extensions (PAE).* 60 | 61 | Linux 62 | ----- 63 | 64 | Download `NI-VISA for Linux`_ 65 | 66 | Supports: 67 | 68 | - openSUSE 12.2 69 | - openSUSE 12.1 70 | - Red Hat Enterprise Linux Desktop + Workstation 6 71 | - Red Hat Enterprise Linux Desktop + Workstation 5 72 | - Scientific Linux 6.x 73 | - Scientific Linux 5.x 74 | 75 | More details details can be found in the `README`_ of the installer. 76 | 77 | .. note:: 78 | 79 | NI-VISA runs on other linux distros but the installation is more 80 | cumbersome. On Arch linux and related distributions, the AUR package 81 | `ni-visa`_ (early development) is known to work for the USB and TCPIP 82 | interfaces. Please note that you should restart after the installation for 83 | things to work properly. 84 | 85 | 86 | .. _`README`: http://download.ni.com/support/softlib//visa/NI-VISA/17.0/Linux/README.txt 87 | .. _`ni-visa`: https://aur.archlinux.org/packages/ni-visa/ 88 | .. _`NI-VISA for Mac OS X`: http://www.ni.com/download/ni-visa-17.5/7224/en/ 89 | .. _`NI-VISA for Windows`: http://www.ni.com/download/ni-visa-17.5/7220/en/ 90 | .. _`NI-VISA for Linux`: http://www.ni.com/download/ni-visa-17.0/6700/en/ 91 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | :orphan: 2 | 3 | 4 | PyVISA: Control your instruments with Python 5 | ============================================ 6 | 7 | .. image:: _static/logo-full.jpg 8 | :alt: PyVISA 9 | :class: floatingflask 10 | 11 | 12 | PyVISA is a Python package that enables you to control all kinds of measurement 13 | devices independently of the interface (e.g. GPIB, RS232, USB, Ethernet). As 14 | an example, reading self-identification from a Keithley Multimeter with GPIB 15 | number 12 is as easy as three lines of Python code:: 16 | 17 | >>> import visa 18 | >>> rm = visa.ResourceManager() 19 | >>> rm.list_resources() 20 | ('ASRL1::INSTR', 'ASRL2::INSTR', 'GPIB0::12::INSTR') 21 | >>> inst = rm.open_resource('GPIB0::12::INSTR') 22 | >>> print(inst.query("*IDN?")) 23 | 24 | (That's the whole program; really!) It works on Windows, Linux and Mac; 25 | with arbitrary adapters (e.g. National Instruments, Agilent, Tektronix, 26 | Stanford Research Systems). 27 | 28 | 29 | General overview 30 | ---------------- 31 | 32 | The programming of measurement instruments can be real pain. There are many 33 | different protocols, sent over many different interfaces and bus systems 34 | (e.g. GPIB, RS232, USB, Ethernet). For every programming language you want 35 | to use, you have to find libraries that support both your device and its bus 36 | system. 37 | 38 | In order to ease this unfortunate situation, the Virtual Instrument Software 39 | Architecture (VISA) specification was defined in the middle of the 90ies. 40 | VISA is a standard for configuring, programming, and troubleshooting 41 | instrumentation systems comprising GPIB, VXI, PXI, Serial, Ethernet, and/or 42 | USB interfaces. 43 | 44 | Today VISA is implemented on all significant operating systems. A couple 45 | of vendors offer VISA libraries, partly with free download. These libraries 46 | work together with arbitrary peripherical devices, although they may be 47 | limited to certain interface devices, such as the vendor's GPIB card. 48 | 49 | The VISA specification has explicit bindings to Visual Basic, C, and G 50 | (LabVIEW’s graphical language). Python can be used to call functions from a 51 | VISA shared library (`.dll`, `.so`, `.dylib`) allowing to directly leverage the 52 | standard implementations. In addition, Python can be used to directly access 53 | most bus systems used by instruments which is why one can envision to implement 54 | the VISA standard directly in Python (see the `PyVISA-Py` project for more 55 | details). PyVISA is both a Python wrapper for VISA shared libraries but 56 | can also serve as a front-end for other VISA implementation such as 57 | `PyVISA-Py`. 58 | 59 | 60 | User guide 61 | ---------- 62 | 63 | .. toctree:: 64 | :maxdepth: 1 65 | 66 | getting 67 | configuring 68 | tutorial 69 | rvalues 70 | example 71 | resources 72 | backends 73 | shell 74 | architecture 75 | 76 | More information 77 | ---------------- 78 | 79 | .. toctree:: 80 | :maxdepth: 1 81 | 82 | names 83 | migrating 84 | contributing 85 | faq 86 | getting_nivisa 87 | api/index 88 | 89 | 90 | .. LocalWords: rst british reST ies vpp pyvisa docs pyvLab 91 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. linkcheck to check all external links for integrity 37 | echo. doctest to run all doctests embedded in the documentation if enabled 38 | goto end 39 | ) 40 | 41 | if "%1" == "clean" ( 42 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 43 | del /q /s %BUILDDIR%\* 44 | goto end 45 | ) 46 | 47 | if "%1" == "html" ( 48 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 49 | if errorlevel 1 exit /b 1 50 | echo. 51 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 52 | goto end 53 | ) 54 | 55 | if "%1" == "dirhtml" ( 56 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 57 | if errorlevel 1 exit /b 1 58 | echo. 59 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 60 | goto end 61 | ) 62 | 63 | if "%1" == "singlehtml" ( 64 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 68 | goto end 69 | ) 70 | 71 | if "%1" == "pickle" ( 72 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished; now you can process the pickle files. 76 | goto end 77 | ) 78 | 79 | if "%1" == "json" ( 80 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished; now you can process the JSON files. 84 | goto end 85 | ) 86 | 87 | if "%1" == "htmlhelp" ( 88 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can run HTML Help Workshop with the ^ 92 | .hhp project file in %BUILDDIR%/htmlhelp. 93 | goto end 94 | ) 95 | 96 | if "%1" == "qthelp" ( 97 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 98 | if errorlevel 1 exit /b 1 99 | echo. 100 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 101 | .qhcp project file in %BUILDDIR%/qthelp, like this: 102 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\pyvisa.qhcp 103 | echo.To view the help file: 104 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\pyvisa.ghc 105 | goto end 106 | ) 107 | 108 | if "%1" == "devhelp" ( 109 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 110 | if errorlevel 1 exit /b 1 111 | echo. 112 | echo.Build finished. 113 | goto end 114 | ) 115 | 116 | if "%1" == "epub" ( 117 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 118 | if errorlevel 1 exit /b 1 119 | echo. 120 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 121 | goto end 122 | ) 123 | 124 | if "%1" == "latex" ( 125 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 129 | goto end 130 | ) 131 | 132 | if "%1" == "text" ( 133 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The text files are in %BUILDDIR%/text. 137 | goto end 138 | ) 139 | 140 | if "%1" == "man" ( 141 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 145 | goto end 146 | ) 147 | 148 | if "%1" == "texinfo" ( 149 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 150 | if errorlevel 1 exit /b 1 151 | echo. 152 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 153 | goto end 154 | ) 155 | 156 | if "%1" == "gettext" ( 157 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 158 | if errorlevel 1 exit /b 1 159 | echo. 160 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 161 | goto end 162 | ) 163 | 164 | if "%1" == "changes" ( 165 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 166 | if errorlevel 1 exit /b 1 167 | echo. 168 | echo.The overview file is in %BUILDDIR%/changes. 169 | goto end 170 | ) 171 | 172 | if "%1" == "linkcheck" ( 173 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 174 | if errorlevel 1 exit /b 1 175 | echo. 176 | echo.Link check complete; look for any errors in the above output ^ 177 | or in %BUILDDIR%/linkcheck/output.txt. 178 | goto end 179 | ) 180 | 181 | if "%1" == "doctest" ( 182 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 183 | if errorlevel 1 exit /b 1 184 | echo. 185 | echo.Testing of doctests in the sources finished, look at the ^ 186 | results in %BUILDDIR%/doctest/output.txt. 187 | goto end 188 | ) 189 | 190 | :end 191 | -------------------------------------------------------------------------------- /docs/migrating.rst: -------------------------------------------------------------------------------- 1 | .. _migrating: 2 | 3 | Migrating from PyVISA < 1.5 4 | =========================== 5 | 6 | .. note:: if you want PyVISA 1.4 compatibility use PyVISA 1.5 that provides 7 | Python 3 support, better visa library detection heuristics, 8 | Windows, Linux and OS X support, and no singleton object. 9 | PyVISA 1.6+ introduces a few compatibility breaks. 10 | 11 | 12 | Some of these decisions were inspired by the ``visalib`` package as a part of Lantz_ 13 | 14 | 15 | Short summary 16 | ------------- 17 | 18 | PyVISA 1.5 has full compatibility with previous versions of PyVISA using the 19 | legacy module (changing some of the underlying implementation). But you are 20 | encouraged to do a few things differently if you want to keep up with the 21 | latest developments and be compatible with PyVISA > 1.5. 22 | 23 | Indeed PyVISA 1.6 breaks compatibility to bring across a few good things. 24 | 25 | **If you are doing:** 26 | 27 | >>> import visa 28 | >>> keithley = visa.instrument("GPIB::12") 29 | >>> print(keithley.ask("*IDN?")) 30 | 31 | change it to: 32 | 33 | >>> import visa 34 | >>> rm = visa.ResourceManager() 35 | >>> keithley = rm.open_resource("GPIB::12") 36 | >>> print(keithley.query("*IDN?")) 37 | 38 | **If you are doing:** 39 | 40 | >>> print(visa.get_instruments_list()) 41 | 42 | change it to: 43 | 44 | >>> print(rm.list_resources()) 45 | 46 | **If you are doing:** 47 | 48 | >>> import pyvisa.vpp43 as vpp43 49 | >>> vpp43.visa_library.load_library("/path/to/my/libvisa.so.7") 50 | 51 | change it to: 52 | 53 | >>> import visa 54 | >>> rm = visa.ResourceManager("/path/to/my/libvisa.so.7") 55 | >>> lib = rm.visalib 56 | 57 | 58 | **If you are doing::** 59 | 60 | >>> vpp43.lock(session) 61 | 62 | change it to:: 63 | 64 | >>> lib.lock(session) 65 | 66 | or better: 67 | 68 | >>> resource.lock() 69 | 70 | 71 | **If you are doing::** 72 | 73 | >>> inst.term_chars = '\r' 74 | 75 | change it to:: 76 | 77 | >>> inst.read_termination = '\r' 78 | >>> inst.write_termination = '\r' 79 | 80 | **If you are doing::** 81 | 82 | >>> print(lib.status) 83 | 84 | change it to:: 85 | 86 | >>> print(lib.last_status) 87 | 88 | or even better, do it per resource:: 89 | 90 | >>> print(rm.last_status) # for the resource manager 91 | >>> print(inst.last_status) # for a specific instrument 92 | 93 | **If you are doing::** 94 | 95 | >>> inst.timeout = 1 # Seconds 96 | 97 | change it to:: 98 | 99 | >>> inst.timeout = 1000 # Milliseconds 100 | 101 | 102 | As you see, most of the code shown above is making a few things explict. 103 | It adds 1 line of code (instantiating the ResourceManager object) 104 | which is not a big deal but it makes things cleaner. 105 | 106 | If you were using ``printf``, ``queryf``, ``scanf``, ``sprintf`` or ``sscanf`` of ``vpp43``, 107 | rewrite as pure Python code (see below). 108 | 109 | If you were using ``Instrument.delay``, change your code or use ``Instrument.query_delay`` 110 | (see below). 111 | 112 | 113 | A few alias has been created to ease the transition: 114 | 115 | - ask -> query 116 | - ask_delay -> query_delay 117 | - get_instrument -> open_resource 118 | 119 | 120 | A more detailed description 121 | --------------------------- 122 | 123 | 124 | Dropped support for string related functions 125 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 126 | 127 | The VISA library includes functions to search and manipulate strings such as ``printf``, 128 | ``queryf``, ``scanf``, ``sprintf`` and ``sscanf``. This makes sense as VISA involves a lot of 129 | string handling operations. The original PyVISA implementation wrapped these functions. 130 | But these operations are easily expressed in pure python and therefore were rarely used. 131 | 132 | PyVISA 1.5 keeps these functions for backwards compatibility but they are removed in 1.6. 133 | 134 | We suggest that you replace such functions by a pure Python version. 135 | 136 | 137 | Isolated low-level wrapping module 138 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 139 | 140 | In the original PyVISA implementation, the low level implementation (``vpp43``) was 141 | mixed with higher level constructs. The VISA library was wrapped using ctypes. 142 | 143 | In 1.5, we refactored it as ``ctwrapper``. This allows us to test the 144 | foreign function calls by isolating them from higher level abstractions. 145 | More importantly, it also allows us to build new low level modules that 146 | can be used as drop in replacements for ``ctwrapper`` in high level modules. 147 | 148 | In 1.6, we made the ``ResourceManager`` the object exposed to the user. The type of the 149 | ``VisaLibrary`` can selected depending of the ``library_path`` and obtained from a plugin 150 | package. 151 | 152 | We have two of such packages planned: 153 | 154 | - a Mock module that allows you to test a PyVISA program even if you do not have 155 | VISA installed. 156 | 157 | - a CFFI based wrapper. CFFI is new python package that allows easier and more 158 | robust wrapping of foreign libraries. It might be part of Python in the future. 159 | 160 | PyVISA 1.5 keeps ``vpp43`` in the legacy subpackage (reimplemented on top of ``ctwrapper``) 161 | to help with the migration. This module is gone in 1.6. 162 | 163 | All functions that were present in ``vpp43`` are now present in ``ctwrapper`` but they 164 | take an additional first parameter: the foreign library wrapper. 165 | 166 | We suggest that you replace ``vpp43`` by accessing the ``VisaLibrary`` object under the attribute 167 | visalib of the resource manager which provides all foreign functions as bound methods (see below). 168 | 169 | 170 | No singleton objects 171 | ~~~~~~~~~~~~~~~~~~~~ 172 | 173 | The original PyVISA implementation relied on a singleton, global objects for the 174 | library wrapper (named ``visa_library``, an instance of the old ``pyvisa.vpp43.VisaLibrary``) 175 | and the resource manager (named ``resource_manager``, and instance of the old 176 | ``pyvisa.visa.ResourceManager``). These were instantiated on import and the user 177 | could rebind to a different library using the ``load_library`` method. Calling this 178 | method however did not affect ``resource_manager`` and might lead to an inconsistent 179 | state. 180 | 181 | There were additionally a few global structures such a ``status`` which stored the last 182 | status returned by the library and the warning context to prevent unwanted warnings. 183 | 184 | In 1.5, there is a new ``VisaLibrary`` class and a new ``ResourceManager`` class (they are 185 | both in ``pyvisa.highlevel``). The new classes are not singletons, at least not in the 186 | strict sense. Multiple instances of ``VisaLibrary`` and ``ResourceManager`` are possible, 187 | but only if they refer to different foreign libraries. In code, this means: 188 | 189 | >>> lib1 = visa.VisaLibrary("/path/to/my/libvisa.so.7") 190 | >>> lib2 = visa.VisaLibrary("/path/to/my/libvisa.so.7") 191 | >>> lib3 = visa.VisaLibrary("/path/to/my/libvisa.so.8") 192 | >>> lib1 is lib2 193 | True 194 | >>> lib1 is lib3 195 | False 196 | 197 | Most of the time, you will not need access to a ``VisaLibrary`` object but to a ``ResourceManager``. 198 | You can do: 199 | 200 | >>> lib = visa.VisaLibrary("/path/to/my/libvisa.so.7") 201 | >>> rm = lib.resource_manager 202 | 203 | or equivalently: 204 | 205 | >>> rm = visa.ResourceManager("/path/to/my/libvisa.so.7") 206 | 207 | .. note:: If the path for the library is not given, the path is obtained from 208 | the user settings file (if exists) or guessed from the OS. 209 | 210 | In 1.6, the state returned by the library is stored per resource. Additionally, 211 | warnings can be silenced by resource as well. You can access with the ``last_status`` 212 | property. 213 | 214 | All together, these changes makes PyVISA thread safe. 215 | 216 | 217 | VisaLibrary methods as way to call Visa functions 218 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 219 | 220 | In the original PyVISA implementation, the ``VisaLibrary`` class was just having 221 | a reference to the ctypes library and a few functions. 222 | 223 | In 1.5, we introduced a new ``VisaLibrary`` class (``pyvisa.highlevel``) which has 224 | every single low level function defined in ``ctwrapper`` as bound methods. In code, 225 | this means that you can do:: 226 | 227 | >>> import visa 228 | >>> rm = visa.ResourceManager("/path/to/my/libvisa.so.7") 229 | >>> lib = rm.visalib 230 | >>> print(lib.read_stb(session)) 231 | 232 | (But it is very likely that you do not have to do it as the resource should have the 233 | function you need) 234 | 235 | It also has every single VISA foreign function in the underlying library as static 236 | method. In code, this means that you can do:: 237 | 238 | >>> status = ctypes.c_ushort() 239 | >>> ret lib.viReadSTB(session, ctypes.byref(status)) 240 | >>> print(ret.value) 241 | 242 | 243 | Ask vs. query 244 | ~~~~~~~~~~~~~ 245 | 246 | Historically, the method ``ask`` has been used in PyVISA to do a ``write`` followed 247 | by a ``read``. But in many other programs this operation is called ``query``. Thereby 248 | we have decided to switch the name, keeping an alias to help with the transition. 249 | 250 | However, ``ask_for_values`` has not been aliased to ``query_values`` because the API 251 | is different. ``ask_for_values`` still uses the old formatting API which is limited 252 | and broken. We suggest that you migrate everything to ``query_values`` 253 | 254 | 255 | Seconds to milliseconds 256 | ~~~~~~~~~~~~~~~~~~~~~~~ 257 | 258 | The timeout is now in milliseconds (not in seconds as it was before). The reason 259 | behind this change is to make it coherent with all other VISA implementations out 260 | there. The C-API, LabVIEW, .NET: all use milliseconds. Using the same units not 261 | only makes it easy to migrate to PyVISA but also allows to profit from all other 262 | VISA docs out there without extra cognitive effort. 263 | 264 | 265 | Removal of Instrument.delay and added Instrument.query_delay 266 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 267 | 268 | In the original PyVISA implementation, ``Instrument`` takes a ``delay`` 269 | argument that adds a pause after each write operation (This also can 270 | be changed using the ``delay`` attribute). 271 | 272 | In PyVISA 1.6, ``delay`` is removed. Delays after write operations must 273 | be added to the application code. Instead, a new attribute and argument 274 | ``query_delay`` is available. This allows you to pause between ``write` and ``read`` 275 | operations inside ``query``. Additionally, ``query`` takes an optional argument 276 | called ``query`` allowing you to change it for each method call. 277 | 278 | 279 | Deprecated term_chars and automatic removal of CR + LF 280 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 281 | 282 | In the original PyVISA implementation, ``Instrument`` takes a ``term_chars`` 283 | argument to change at the read and write termination characters. If this 284 | argument is ``None``, ``CR + LF`` is appended to each outgoing message and 285 | not expected for incoming messages (although removed if present). 286 | 287 | In PyVISA 1.6, ``term_chars`` is replaced by ``read_termination` and 288 | ``write_termination``. In this way, you can set independently the termination 289 | for each operation. Automatic removal of ``CR + LF`` is also gone in 1.6. 290 | 291 | 292 | 293 | 294 | .. _Lantz: https://lantz.readthedocs.org/ 295 | -------------------------------------------------------------------------------- /docs/names.rst: -------------------------------------------------------------------------------- 1 | 2 | .. _resource_names: 3 | 4 | VISA resource names 5 | =================== 6 | 7 | If you use the function :func:`open_resource`, you must tell this 8 | function the *VISA resource name* of the instrument you want to 9 | connect to. Generally, it starts with the bus type, followed by a 10 | double colon ``"::"``, followed by the number within the bus. For 11 | example, 12 | 13 | .. code-block:: none 14 | 15 | GPIB::10 16 | 17 | denotes the GPIB instrument with the number 10. If you have two GPIB 18 | boards and the instrument is connected to board number 1, you must 19 | write 20 | 21 | .. code-block:: none 22 | 23 | GPIB1::10 24 | 25 | As for the bus, things like ``"GPIB"``, ``"USB"``, ``"ASRL"`` (for 26 | serial/parallel interface) are possible. So for connecting to an 27 | instrument at COM2, the resource name is 28 | 29 | .. code-block:: none 30 | 31 | ASRL2 32 | 33 | (Since only one instrument can be connected with one serial interface, 34 | there is no double colon parameter.) However, most VISA systems allow 35 | aliases such as ``"COM2"`` or ``"LPT1"``. You may also add your own 36 | aliases. 37 | 38 | The resource name is case-insensitive. It doesn't matter whether you 39 | say ``"ASRL2"`` or ``"asrl2"``. For further information, I have to refer 40 | you to a comprehensive VISA description like 41 | ``_. 42 | 43 | 44 | VISA Resource Syntax and Examples 45 | --------------------------------- 46 | 47 | (This is adapted from the VISA manual) 48 | 49 | The following table shows the grammar for the address string. Optional string segments are shown in square brackets ([ ]). 50 | 51 | ================= ======================================================================================== 52 | Interface Syntax 53 | ================= ======================================================================================== 54 | ENET-Serial INSTR ASRL[0]::host address::serial port::INSTR 55 | ----------------- ---------------------------------------------------------------------------------------- 56 | GPIB INSTR GPIB[board]::primary address[::secondary address][::INSTR] 57 | GPIB INTFC GPIB[board]::INTFC 58 | ----------------- ---------------------------------------------------------------------------------------- 59 | PXI BACKPLANE PXI[interface]::chassis number::BACKPLANE 60 | PXI INSTR PXI[bus]::device[::function][::INSTR] 61 | PXI INSTR PXI[interface]::bus-device[.function][::INSTR] 62 | PXI INSTR PXI[interface]::CHASSISchassis number::SLOTslot number[::FUNCfunction][::INSTR] 63 | PXI MEMACC PXI[interface]::MEMACC 64 | ----------------- ---------------------------------------------------------------------------------------- 65 | Remote NI-VISA visa://host address[:server port]/remote resource 66 | ----------------- ---------------------------------------------------------------------------------------- 67 | Serial INSTR ASRLboard[::INSTR] 68 | ----------------- ---------------------------------------------------------------------------------------- 69 | TCPIP INSTR TCPIP[board]::host address[::LAN device name][::INSTR] 70 | TCPIP SOCKET TCPIP[board]::host address::port::SOCKET 71 | ----------------- ---------------------------------------------------------------------------------------- 72 | USB INSTR USB[board]::manufacturer ID::model code::serial number[::USB interface number][::INSTR] 73 | USB RAW USB[board]::manufacturer ID::model code::serial number[::USB interface number]::RAW 74 | ----------------- ---------------------------------------------------------------------------------------- 75 | VXI BACKPLANE VXI[board][::VXI logical address]::BACKPLANE 76 | VXI INSTR VXI[board]::VXI logical address[::INSTR] 77 | VXI MEMACC VXI[board]::MEMACC 78 | VXI SERVANT VXI[board]::SERVANT 79 | ================= ======================================================================================== 80 | 81 | Use the GPIB keyword to establish communication with GPIB resources. Use the VXI keyword for VXI resources via embedded, MXIbus, or 1394 controllers. Use the ASRL keyword to establish communication with an asynchronous serial (such as RS-232 or RS-485) device. Use the PXI keyword for PXI and PCI resources. Use the TCPIP keyword for Ethernet communication. 82 | 83 | The following table shows the default value for optional string segments. 84 | 85 | 86 | ======================== ================================== 87 | Optional String Segments Default Value 88 | ======================== ================================== 89 | board 0 90 | GPIB secondary address none 91 | LAN device name inst0 92 | PXI bus 0 93 | PXI function 0 94 | USB interface number lowest numbered relevant interface 95 | ======================== ================================== 96 | 97 | 98 | The following table shows examples of address strings: 99 | 100 | ================================ ============================================= 101 | Address String Description 102 | ================================ ============================================= 103 | ASRL::1.2.3.4::2::INSTR A serial device attached to port 2 of the 104 | ENET Serial controller at address 1.2.3.4. 105 | -------------------------------- --------------------------------------------- 106 | ASRL1::INSTR A serial device attached to interface ASRL1. 107 | -------------------------------- --------------------------------------------- 108 | GPIB::1::0::INSTR A GPIB device at primary address 1 and 109 | secondary address 0 in GPIB interface 0. 110 | -------------------------------- --------------------------------------------- 111 | GPIB2::INTFC Interface or raw board resource for GPIB 112 | interface 2. 113 | -------------------------------- --------------------------------------------- 114 | PXI::15::INSTR PXI device number 15 on bus 0 with implied 115 | function 0. 116 | -------------------------------- --------------------------------------------- 117 | PXI::2::BACKPLANE Backplane resource for chassis 2 on the 118 | default PXI system, which is interface 0. 119 | -------------------------------- --------------------------------------------- 120 | PXI::CHASSIS1::SLOT3 PXI device in slot number 3 of the PXI chassis 121 | configured as chassis 1. 122 | -------------------------------- --------------------------------------------- 123 | PXI0::2-12.1::INSTR PXI bus number 2, device 12 with function 1. 124 | -------------------------------- --------------------------------------------- 125 | PXI0::MEMACC PXI MEMACC session. 126 | -------------------------------- --------------------------------------------- 127 | TCPIP::dev.company.com::INSTR A TCP/IP device using VXI-11 or LXI located at 128 | the specified address. This uses the default 129 | LAN Device Name of inst0. 130 | -------------------------------- --------------------------------------------- 131 | TCPIP0::1.2.3.4::999::SOCKET Raw TCP/IP access to port 999 at the specified 132 | IP address. 133 | -------------------------------- --------------------------------------------- 134 | USB::0x1234::125::A22-5::INSTR A USB Test & Measurement class device with 135 | manufacturer ID 0x1234, model code 125, and 136 | serial number A22-5. This uses the device's 137 | first available USBTMC interface. This is 138 | usually number 0. 139 | -------------------------------- --------------------------------------------- 140 | USB::0x5678::0x33::SN999::1::RAW A raw USB nonclass device with manufacturer 141 | ID 0x5678, model code 0x33, and serial number 142 | SN999. This uses the device's interface number 1. 143 | -------------------------------- --------------------------------------------- 144 | visa://hostname/ASRL1::INSTR The resource ASRL1::INSTR on the specified 145 | remote system. 146 | -------------------------------- --------------------------------------------- 147 | VXI::1::BACKPLANE Mainframe resource for chassis 1 on the default 148 | VXI system, which is interface 0. 149 | -------------------------------- --------------------------------------------- 150 | VXI::MEMACC Board-level register access to the VXI interface. 151 | -------------------------------- --------------------------------------------- 152 | VXI0::1::INSTR A VXI device at logical address 1 in VXI 153 | interface VXI0. 154 | -------------------------------- --------------------------------------------- 155 | VXI0::SERVANT Servant/device-side resource for VXI interface 0. 156 | ================================ ============================================= 157 | 158 | -------------------------------------------------------------------------------- /docs/resources.rst: -------------------------------------------------------------------------------- 1 | .. _resources: 2 | 3 | Resources 4 | ========= 5 | 6 | A resource represents an instrument, e.g. a measurement device. There are 7 | multiple classes derived from resources representing the different available 8 | types of resources (eg. GPIB, Serial). Each contains the particular set of 9 | attributes an methods that are available by the underlying device. 10 | 11 | You do not create this objects directly but they are returned by the 12 | :meth:`pyvisa.highlevel.ResourceManager.open_resource` method of a :class:`pyvisa.highlevel.ResourceManager`. In general terms, there 13 | are two main groups derived from :class:`pyvisa.resources.Resource`, :class:`pyvisa.resources.RegisterBasedResource` and :class:`pyvisa.resources.MessageBasedResource`. 14 | 15 | .. note:: The resource Python class to use is selected automatically from the 16 | resource name. However, you can force a Resource Python class: 17 | 18 | >>> from pyvisa.resources import MessageBasedResource 19 | >>> inst = rm.open('ASRL1::INSTR', resource_pyclass=MessageBasedResource) 20 | 21 | 22 | The following sections explore the most common attributes of ``Resource`` and 23 | ``MessageBased`` (Serial, GPIB, etc) which are the ones you will encounte more 24 | often. For more information, refer to the :ref:`api`. 25 | 26 | 27 | Attributes Resource 28 | ------------------- 29 | 30 | session 31 | ~~~~~~~ 32 | 33 | Each communication channel to an instrument has a session handle which is unique. 34 | You can get this value:: 35 | 36 | >>> my_device.session 37 | 10442240 38 | 39 | If the resource is closed, an exception will be raised: 40 | 41 | >>> inst.close() 42 | >>> inst.session 43 | Traceback (most recent call last): 44 | ... 45 | pyvisa.errors.InvalidSession: Invalid session handle. The resource might be closed. 46 | 47 | 48 | timeout 49 | ~~~~~~~ 50 | 51 | Very most VISA I/O operations may be performed with a timeout. If a timeout is 52 | set, every operation that takes longer than the timeout is aborted and an 53 | exception is raised. Timeouts are given per instrument in **milliseconds**. 54 | 55 | For all PyVISA objects, a timeout is set with 56 | 57 | .. code-block:: python 58 | 59 | my_device.timeout = 25000 60 | 61 | Here, ``my_device`` may be a device, an interface or whatever, and its timeout is 62 | set to 25 seconds. To set an **infinite** timeout, set it to ``None`` or ``float('+inf')`` or: 63 | 64 | .. code-block:: python 65 | 66 | del my_device.timeout 67 | 68 | To set it to **immediate**, set it to `0` or a negative value. (Actually, any value 69 | smaller than 1 is considered immediate) 70 | 71 | Now every operation of the resource takes as long as it takes, even 72 | indefinitely if necessary. 73 | 74 | 75 | Attributes of MessageBase resources 76 | ----------------------------------- 77 | 78 | .. _sec:chunk-length: 79 | 80 | Chunk length 81 | ~~~~~~~~~~~~ 82 | 83 | If you read data from a device, you must store it somewhere. Unfortunately, 84 | PyVISA must make space for the data *before* it starts reading, which means 85 | that it must know how much data the device will send. However, it doesn't know 86 | a priori. 87 | 88 | Therefore, PyVISA reads from the device in *chunks*. Each chunk is 89 | 20 kilobytes long by default. If there's still data to be read, PyVISA repeats 90 | the procedure and eventually concatenates the results and returns it to you. 91 | Those 20 kilobytes are large enough so that mostly one read cycle is 92 | sufficient. 93 | 94 | The whole thing happens automatically, as you can see. Normally 95 | you needn't worry about it. However, some devices don't like to send data in 96 | chunks. So if you have trouble with a certain device and expect data lengths 97 | larger than the default chunk length, you should increase its value by saying 98 | e.g. :: 99 | 100 | my_instrument.chunk_size = 102400 101 | 102 | This example sets it to 100 kilobytes. 103 | 104 | 105 | .. _sec:termchars: 106 | 107 | Termination characters 108 | ---------------------- 109 | 110 | Somehow the computer must detect when the device is finished with sending a 111 | message. It does so by using different methods, depending on the bus system. 112 | In most cases you don't need to worry about termination characters because the 113 | defaults are very good. However, if you have trouble, you may influence 114 | termination characters with PyVISA. 115 | 116 | Termination characters may be one character or a sequence of characters. 117 | Whenever this character or sequence 118 | occurs in the input stream, the read operation is terminated and the read 119 | message is given to the calling application. The next read operation continues 120 | with the input stream immediately after the last termination sequence. In 121 | PyVISA, the termination characters are stripped off the message before it is 122 | given to you. 123 | 124 | You may set termination characters for each instrument, e.g. 125 | 126 | .. code-block:: python 127 | 128 | my_instrument.read_termination = '\r' 129 | 130 | ('\r' is carriage return, usually appearing in the manuals as CR) 131 | 132 | Alternatively you can give it when creating your instrument object:: 133 | 134 | my_instrument = rm.open_resource("GPIB::10", read_termination='\r') 135 | 136 | The default value depends on the bus system. Generally, the sequence is empty, 137 | in particular for GPIB. For RS232 it's ``\r``. 138 | 139 | You can specify the character to add to each outgoing message using the 140 | ``write_termination`` attribute. 141 | 142 | 143 | `query_delay` and `send_end` 144 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 145 | 146 | .. index:: 147 | single: query_delay 148 | single: send_end 149 | 150 | There are two further options related to message termination, namely 151 | ``send_end`` and ``query_delay``. ``send_end`` is a boolean. If it's ``True`` (the 152 | default), the EOI line is asserted after each write operation, signalling the 153 | end of the operation. EOI is GPIB-specific but similar action is taken for 154 | other interfaces. 155 | 156 | The argument ``query_delay`` is the time in seconds to wait after 157 | each write operation. So you could write:: 158 | 159 | my_instrument = rm.open_resource("GPIB::10", send_end=False, delay=1.2) 160 | 161 | .. index:: single: EOI line 162 | 163 | This will set the delay to 1.2 seconds, and the EOI line is omitted. By the 164 | way, omitting EOI is *not* recommended, so if you omit it nevertheless, you 165 | should know what you're doing. 166 | 167 | -------------------------------------------------------------------------------- /docs/rvalues.rst: -------------------------------------------------------------------------------- 1 | .. _rvalues: 2 | 3 | Reading and Writing values 4 | ========================== 5 | 6 | Some instruments allow to transfer to and from the computer larger datasets 7 | with a single query. A typical example is an oscilloscope, which you can query 8 | for the whole voltage trace. Or an arbitrary wave generator to which you 9 | have to transfer the function you want to generate. 10 | 11 | Basically, data like this can be transferred in two ways: in ASCII form (slow, 12 | but human readable) and binary (fast, but more difficult to debug). 13 | 14 | PyVISA Message Based Resources have two different methods for this 15 | called :meth:`pyvisa.resources.MessageBasedResource.query_ascii_values` 16 | and :meth:`pyvisa.resources.MessageBasedResource.query_binary_values`. 17 | It also has the convenient :meth:`pyvisa.resources.MessageBasedResource.query_values` 18 | which will use follow a previously established configuration. 19 | 20 | 21 | Reading ASCII values 22 | -------------------- 23 | 24 | If your oscilloscope (open in the variable ``inst``) has been configured to 25 | transfer data in **ASCII** when the ``CURV?`` command is issued, you can just 26 | query the values like this:: 27 | 28 | >>> values = inst.query_ascii_values('CURV?') 29 | 30 | ``values`` will be ``list`` containing the values from the device. 31 | 32 | In many cases you do not want a ``list`` but rather a different container type such 33 | as a ``numpy.array``. You can of course cast the data afterwards like this:: 34 | 35 | >>> values = np.array(inst.query_ascii_values('CURV?')) 36 | 37 | but sometimes it is much more efficient to avoid the intermediate list, and in this case 38 | you can just specify the container type in the query:: 39 | 40 | >>> values = inst.query_ascii_values('CURV?', container=numpy.array) 41 | 42 | In ``container`` you can have any callable/type that takes an iterable. 43 | 44 | Some devices transfer data in ASCII but not as decimal numbers but rather hex 45 | or oct. Or you might want to receive an array of strings. In that case you can specify 46 | a ``converter``. For example, if you expect to receive integers as hex: 47 | 48 | >>> values = inst.query_ascii_values('CURV?', converter='x') 49 | 50 | ``converter`` can be one of the Python :ref:`string formatting codes `. 51 | But you can also specify a callable that takes a single argument if needed. 52 | The default converter is ``'f'``. 53 | 54 | Finally, some devices might return the values separated in an uncommon way. For example 55 | if the returned values are separated by a ``'$'`` you can do the following call: 56 | 57 | >>> values = inst.query_ascii_values('CURV?', separator='$') 58 | 59 | You can provide a function to takes a string and returns an iterable. 60 | Default value for the separator is ``','`` (comma) 61 | 62 | .. _sec:reading-binary-data: 63 | 64 | 65 | Reading binary values 66 | --------------------- 67 | 68 | If your oscilloscope (open in the variable ``inst``) has been configured to 69 | transfer data in **BINARY** when the ``CURV?`` command is issued, you need to 70 | know which type datatype (e.g. uint8, int8, single, double, etc) is being 71 | used. PyVISA use the same naming convention as the :ref:`struct module `. 72 | 73 | You also need to know the *endianness*. PyVISA assumes little-endian as default. 74 | If you have doubles `d` in big endian the call will be:: 75 | 76 | >>> values = inst.query_binary_values('CURV?', datatype='d', is_big_endian=True) 77 | 78 | You can also specify the output container type, just as it was shown before. 79 | 80 | By default, PyVISA will assume that the data block is formatted according to 81 | the IEEE convention. If your instrument uses HP data block you can pass 82 | ``header_fmt='hp'`` to ``read_binary_values``. If your instrument does not use 83 | any header for the data simply ``header_fmt='empty'``. 84 | 85 | By default PyVISA assumes, that the instrument will add the termination 86 | character at the end of the data block and actually makes sure it reads it to 87 | avoid issues. This behavior fits well a number of devices. However some devices 88 | omit the termination character, in which cases the operation will timeout. 89 | In this situation, first makes sure you can actually read from the instrument 90 | by reading the answer using the ``read_raw`` function (you may need to call it 91 | multiple time), and check that the advertized length of the block match what 92 | you get from your instrument (plus the header). If it is so, then you can 93 | safely pass ``expect_termination=False``, and PyVISA will not look for a 94 | termination character at the end of the message. 95 | 96 | 97 | Writing ASCII values 98 | -------------------- 99 | 100 | To upload a function shape to arbitrary wave generator, the command might be 101 | ``WLISt:WAVeform:DATA ,`` where ```` 102 | tells the device under which name to store the data. 103 | 104 | >>> values = list(range(100)) 105 | >>> inst.write_ascii_values('WLISt:WAVeform:DATA somename,', values) 106 | 107 | Again, you can specify the converter code. 108 | 109 | >>> inst.write_ascii_values('WLISt:WAVeform:DATA somename,', values, converter='x') 110 | 111 | ``converter`` can be one of the Python :ref:`string formatting codes `. 112 | But you can also specify a callable that takes a single argument if needed. 113 | The default converter is ``'f'``. 114 | 115 | The separator can also be specified just like in ``query_ascii_values``. 116 | 117 | >>> inst.write_ascii_values('WLISt:WAVeform:DATA somename,', values, converter='x', separator='$') 118 | 119 | You can provide a function to takes a iterable and returns an string. 120 | Default value for the separator is ``','`` (comma) 121 | 122 | 123 | Writing binary values 124 | --------------------- 125 | 126 | To upload a function shape to arbitrary wave generator, the command might be 127 | ``WLISt:WAVeform:DATA ,`` where ```` 128 | tells the device under which name to store the data. 129 | 130 | >>> values = list(range(100)) 131 | >>> inst.write_binary_values('WLISt:WAVeform:DATA somename,', values) 132 | 133 | Again you can specify the ``datatype`` and ``endianness``. 134 | 135 | >>> inst.write_binary_values('WLISt:WAVeform:DATA somename,', values, datatype='d', is_big_endian=False) 136 | 137 | 138 | 139 | Preconfiguring the transfer format 140 | ---------------------------------- 141 | 142 | Most of the cases, each device will transfer data in the same format every time. 143 | And making the call so detailed everytime can be annoying. For this purpose, 144 | PyVISA provides a way to preconfigure the default. Each Message Based 145 | Resources exposes an attribute named ``values_format`` which is an object with the following 146 | properties: ``is_binary``, ``datatype``, ``is_big_endian``, ``container``. For example to set 147 | e.g. little-endian doubles and a numpy array:: 148 | 149 | >>> inst.values_format.is_binary = True 150 | >>> inst.values_format.datatype = 'd' 151 | >>> inst.values_format.is_big_endian = False 152 | >>> inst.values_format.container = numpy.array 153 | 154 | or shorter: 155 | 156 | >>> inst.values_format.use_binary('d', False, numpy.array) 157 | 158 | After doing this, you can simply call:: 159 | 160 | >>> inst.query_values('CURV?') 161 | 162 | which will dispatch to the appropriate function and arguments. 163 | 164 | If you want to default to ASCII transfer, preconfiguring is a little bit more 165 | cumbersome as you need to specify the converters for both ways. 166 | 167 | For example with hex, with ``'$'`` as separator: 168 | 169 | >>> inst.values_format.is_binary = False 170 | >>> inst.values_format.converter = 'x' 171 | >>> inst.values_format.separator = '$' 172 | >>> inst.values_format.container = numpy.array 173 | 174 | or shorter: 175 | 176 | >>> inst.values_format.use_ascii('x', '$', numpy.array) 177 | 178 | 179 | This works for both query and write operations. 180 | 181 | 182 | When things are not what they should be 183 | --------------------------------------- 184 | 185 | PyVISA provides an easy way to transfer data from and to the device. The methods 186 | described above work fine for 99% of the cases but there is always a particular 187 | device that do not follow any of the standard protocols and is so different that 188 | cannot be adapted with the arguments provided above. 189 | 190 | In those cases, you need to get the data:: 191 | 192 | >>> inst.write('CURV?') 193 | >>> data = inst.read_raw() 194 | 195 | and then you need to implement the logic to parse it. 196 | 197 | Alternatively if the `read_raw` call fails you can try to read just a few bytes 198 | using:: 199 | 200 | >>> inst.write('CURV?') 201 | >>> data = inst.read_bytes(1) 202 | 203 | If this call fails it may mean that your instrument did not answer, either 204 | because it needs more time or because your first instruction was not 205 | understood. 206 | -------------------------------------------------------------------------------- /docs/shell.rst: -------------------------------------------------------------------------------- 1 | .. _shell: 2 | 3 | PyVISA Shell 4 | ============ 5 | 6 | The shell, moved into PyVISA from the Lantz_ Project is a text based user 7 | interface to interact with instruments. You can invoke it from the command-line:: 8 | 9 | python -m visa shell 10 | 11 | or:: 12 | 13 | pyvisa-shell 14 | 15 | that will show something the following prompt:: 16 | 17 | Welcome to the VISA shell. Type help or ? to list commands. 18 | 19 | (visa) 20 | 21 | At any time, you can type ``?`` or ``help`` to get a list of valid commands:: 22 | 23 | (visa) help 24 | 25 | Documented commands (type help ): 26 | ======================================== 27 | EOF attr close exit help list open query read timeout write 28 | 29 | (visa) help list 30 | List all connected resources. 31 | 32 | Tab completion is also supported. 33 | 34 | The most basic task is listing all connected devices:: 35 | 36 | (visa) list 37 | ( 0) ASRL1::INSTR 38 | ( 1) ASRL2::INSTR 39 | ( 2) USB0::0x1AB1::0x0588::DS1K00005888::INSTR 40 | 41 | 42 | Each device/port is assigned a number that you can use for subsequent commands. 43 | Let's open comport 1:: 44 | 45 | (visa) open 0 46 | ASRL1::INSTR has been opened. 47 | You can talk to the device using "write", "read" or "query. 48 | The default end of message is added to each message 49 | (open) query *IDN? 50 | Some Instrument, Some Company. 51 | 52 | You can print timeout that is set for query/read operation:: 53 | 54 | (open) timeout 55 | Timeout: 2000ms 56 | 57 | Then also to change the timeout for example to 1500ms (1.5 sec):: 58 | 59 | (open) timeout 1500 60 | Done 61 | 62 | We can also get a list of all visa attributes:: 63 | 64 | (open) attr 65 | +-----------------------------+------------+----------------------------+-------------------------------------+ 66 | | VISA name | Constant | Python name | val | 67 | +-----------------------------+------------+----------------------------+-------------------------------------+ 68 | | VI_ATTR_ASRL_ALLOW_TRANSMIT | 1073676734 | allow_transmit | 1 | 69 | | VI_ATTR_ASRL_AVAIL_NUM | 1073676460 | bytes_in_buffer | 0 | 70 | | VI_ATTR_ASRL_BAUD | 1073676321 | baud_rate | 9600 | 71 | | VI_ATTR_ASRL_BREAK_LEN | 1073676733 | break_length | 250 | 72 | | VI_ATTR_ASRL_BREAK_STATE | 1073676732 | break_state | 0 | 73 | | VI_ATTR_ASRL_CONNECTED | 1073676731 | | VI_ERROR_NSUP_ATTR | 74 | | VI_ATTR_ASRL_CTS_STATE | 1073676462 | | 0 | 75 | | VI_ATTR_ASRL_DATA_BITS | 1073676322 | data_bits | 8 | 76 | | VI_ATTR_ASRL_DCD_STATE | 1073676463 | | 0 | 77 | | VI_ATTR_ASRL_DISCARD_NULL | 1073676464 | discard_null | 0 | 78 | | VI_ATTR_ASRL_DSR_STATE | 1073676465 | | 0 | 79 | | VI_ATTR_ASRL_DTR_STATE | 1073676466 | | 1 | 80 | | VI_ATTR_ASRL_END_IN | 1073676467 | end_input | 2 | 81 | | VI_ATTR_ASRL_END_OUT | 1073676468 | | 0 | 82 | | VI_ATTR_ASRL_FLOW_CNTRL | 1073676325 | | 0 | 83 | | VI_ATTR_ASRL_PARITY | 1073676323 | parity | 0 | 84 | | VI_ATTR_ASRL_REPLACE_CHAR | 1073676478 | replace_char | 0 | 85 | | VI_ATTR_ASRL_RI_STATE | 1073676479 | | 0 | 86 | | VI_ATTR_ASRL_RTS_STATE | 1073676480 | | 1 | 87 | | VI_ATTR_ASRL_STOP_BITS | 1073676324 | stop_bits | 10 | 88 | | VI_ATTR_ASRL_WIRE_MODE | 1073676735 | | 128 | 89 | | VI_ATTR_ASRL_XOFF_CHAR | 1073676482 | xoff_char | 19 | 90 | | VI_ATTR_ASRL_XON_CHAR | 1073676481 | xon_char | 17 | 91 | | VI_ATTR_DMA_ALLOW_EN | 1073676318 | allow_dma | 0 | 92 | | VI_ATTR_FILE_APPEND_EN | 1073676690 | | 0 | 93 | | VI_ATTR_INTF_INST_NAME | 3221160169 | | ASRL1 (/dev/cu.Bluetooth-PDA-Sync) | 94 | | VI_ATTR_INTF_NUM | 1073676662 | interface_number | 1 | 95 | | VI_ATTR_INTF_TYPE | 1073676657 | | 4 | 96 | | VI_ATTR_IO_PROT | 1073676316 | io_protocol | 1 | 97 | | VI_ATTR_MAX_QUEUE_LENGTH | 1073676293 | | 50 | 98 | | VI_ATTR_RD_BUF_OPER_MODE | 1073676330 | | 3 | 99 | | VI_ATTR_RD_BUF_SIZE | 1073676331 | | 4096 | 100 | | VI_ATTR_RM_SESSION | 1073676484 | | 3160976 | 101 | | VI_ATTR_RSRC_CLASS | 3221159937 | resource_class | INSTR | 102 | | VI_ATTR_RSRC_IMPL_VERSION | 1073676291 | implementation_version | 5243392 | 103 | | VI_ATTR_RSRC_LOCK_STATE | 1073676292 | lock_state | 0 | 104 | | VI_ATTR_RSRC_MANF_ID | 1073676661 | | 4086 | 105 | | VI_ATTR_RSRC_MANF_NAME | 3221160308 | resource_manufacturer_name | National Instruments | 106 | | VI_ATTR_RSRC_NAME | 3221159938 | resource_name | ASRL1::INSTR | 107 | | VI_ATTR_RSRC_SPEC_VERSION | 1073676656 | spec_version | 5243136 | 108 | | VI_ATTR_SEND_END_EN | 1073676310 | send_end | 1 | 109 | | VI_ATTR_SUPPRESS_END_EN | 1073676342 | | 0 | 110 | | VI_ATTR_TERMCHAR | 1073676312 | | 10 | 111 | | VI_ATTR_TERMCHAR_EN | 1073676344 | | 0 | 112 | | VI_ATTR_TMO_VALUE | 1073676314 | | 2000 | 113 | | VI_ATTR_TRIG_ID | 1073676663 | | -1 | 114 | | VI_ATTR_WR_BUF_OPER_MODE | 1073676333 | | 2 | 115 | | VI_ATTR_WR_BUF_SIZE | 1073676334 | | 4096 | 116 | +-----------------------------+------------+----------------------------+-------------------------------------+ 117 | 118 | 119 | To simplify the handling of VI_ATTR_TERMCHAR and VI_ATTR_TERMCHAR_EN, the command 'termchar' can be used. 120 | If only one character provided, it sets both read and write termination character to the same character. 121 | If two characters are provided, it sets read and write termination characters independently. 122 | 123 | To setup termchar to '\r' (CR or ascii code 10):: 124 | 125 | (open) termchar CR 126 | Done 127 | 128 | To read what termchar is defined:: 129 | 130 | (open) termchar 131 | Termchar read: CR write: CR 132 | 133 | To setup read termchar to '\n' and write termchar to '\r\n\':: 134 | 135 | (open) termchar LF CRLF 136 | Done 137 | 138 | Supported termchar values are: CR ('\r'), LF ('\n'), CRLF ('\r\n') , NUL ('\0'), None. 139 | None is used to disable termchar. 140 | 141 | 142 | Finally, you can close the device:: 143 | 144 | (open) close 145 | 146 | 147 | PyVisa Shell Backends 148 | ===================== 149 | 150 | Based on available backend (see bellow for ``info`` command), it is possible to switch shell to use non-default backend via 151 | ``-b BACKEND`` or ``--backend BACKEND``. 152 | 153 | You can invoke:: 154 | 155 | python -m visa -b sim shell 156 | 157 | or:: 158 | 159 | pyvisa-shell -b sim 160 | 161 | to use python-sim as backend instead of ni backend. 162 | This can be used for example for testing of python-sim configuration. 163 | 164 | You can invoke:: 165 | 166 | python -m visa -b py shell 167 | 168 | or:: 169 | 170 | pyvisa-shell -b py 171 | 172 | uses python-py as backend instead of ni backend, for situation when ni not installed. 173 | 174 | 175 | PyVisa Info 176 | =========== 177 | 178 | You can invoke it from the command-line:: 179 | 180 | python -m visa info 181 | 182 | or:: 183 | 184 | pyvisa-info 185 | 186 | that will print information to diagnose PyVISA, info about Machine, Python, backends, etc :: 187 | 188 | Machine Details: 189 | Platform ID: Windows 190 | Processor: Intel64 Family 6 191 | ... 192 | PyVISA Version: ... 193 | 194 | Backends: 195 | ni: 196 | Version: 1.8 (bundled with PyVISA) 197 | ... 198 | py: 199 | Version: 0.2 200 | ... 201 | sim: 202 | Version: 0.3 203 | Spec version: 1.1 204 | 205 | 206 | Summary 207 | ======= 208 | 209 | Cool, right? It will be great to have a GUI similar to NI-MAX, but we leave that to be developed outside PyVISA. 210 | Want to help? Let us know! 211 | 212 | 213 | .. _`Lantz`: https://lantz.readthedocs.org 214 | 215 | -------------------------------------------------------------------------------- /docs/tutorial.rst: -------------------------------------------------------------------------------- 1 | .. _tutorial: 2 | 3 | Tutorial 4 | ======== 5 | 6 | .. note:: If you have been using PyVISA before version 1.5, you might want to 7 | read :ref:`migrating`. 8 | 9 | 10 | An example 11 | ---------- 12 | 13 | Let's go *in medias res* and have a look at a simple example:: 14 | 15 | >>> import visa 16 | >>> rm = visa.ResourceManager() 17 | >>> rm.list_resources() 18 | ('ASRL1::INSTR', 'ASRL2::INSTR', 'GPIB0::14::INSTR') 19 | >>> my_instrument = rm.open_resource('GPIB0::14::INSTR') 20 | >>> print(my_instrument.query('*IDN?')) 21 | 22 | This example already shows the two main design goals of PyVISA: preferring 23 | simplicity over generality, and doing it the object-oriented way. 24 | 25 | After importing ``visa``, we create a ``ResourceManager`` object. If called 26 | without arguments, PyVISA will use the default backend (NI) which tries to find 27 | the VISA shared library for you. You can check, the location of the shared 28 | library used simply by: 29 | 30 | >>> print(rm) 31 | 32 | 33 | .. note:: 34 | 35 | In some cases, PyVISA is not able to find the library for you resulting in 36 | an ``OSError``. To fix it, find the library path yourself and pass it to 37 | the ResourceManager constructor. You can also specify it in a configuration 38 | file as discussed in :ref:`configuring`. 39 | 40 | 41 | Once that you have a ``ResourceManager``, you can list the available resources 42 | using the ``list_resources`` method. The output is a tuple listing the 43 | :ref:`resource_names`. You can use a dedicated regular expression syntax to 44 | filter the instruments discovered by this method. The syntax is described in 45 | details in :py:meth:`~pyvisa.highlevel.ResourceManager.list_resources`. The 46 | default value is '?*::INSTR' which means that by default only instrument 47 | whose resource name ends with '::INSTR' (in particular USB RAW resources and 48 | TCPIP SOCKET resources are not listed). 49 | 50 | In this case, there is a GPIB instrument with instrument number 14, so you ask 51 | the ``ResourceManager`` to open "'GPIB0::14::INSTR'" and assign the returned 52 | object to the *my_instrument*. 53 | 54 | Notice ``open_resource`` has given you an instance of ``GPIBInstrument`` class 55 | (a subclass of the more generic ``Resource``). 56 | 57 | >>> print(my_instrument) 58 | 59 | 60 | There many ``Resource`` subclasses representing the different types of 61 | resources, but you do not have to worry as the ``ResourceManager`` will provide 62 | you with the appropriate class. You can check the methods and attributes of 63 | each class in the :ref:`api_resources` 64 | 65 | Then, you query the device with the following message: ``'\*IDN?'``. 66 | Which is the standard GPIB message for "what are you?" or -- in some cases -- 67 | "what's on your display at the moment?". ``query`` is a short form for a 68 | ``write`` operation to send a message, followed by a ``read``. 69 | 70 | So:: 71 | 72 | >>> my_instrument.query("*IDN?") 73 | 74 | is the same as:: 75 | 76 | >>> my_instrument.write('*IDN?') 77 | >>> print(my_instrument.read()) 78 | 79 | 80 | Example for serial (RS232) device 81 | --------------------------------- 82 | 83 | Consider an Oxford ITC4 temperature controller, which is connected 84 | through COM2 with my computer. The following code prints its 85 | self-identification on the screen:: 86 | 87 | itc4 = rm.open_resource("COM2") 88 | itc4.write("V") 89 | print(itc4.read()) 90 | 91 | Instead of separate write and read operations, you can do both with 92 | one ``query()`` call. Thus, the above source code is equivalent to:: 93 | 94 | print(itc4.query("V")) 95 | 96 | It couldn't be simpler. 97 | -------------------------------------------------------------------------------- /examples/itc4.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # itc4.py - PyVISA test code for Oxfort ITC4 temperature controller 5 | # 6 | # Copyright © 2005, 2006, 2007, 2008 7 | # Torsten Bronger , 8 | # Gregor Thalhammer . 9 | # 10 | # This file is part of PyVISA. 11 | # 12 | # PyVISA is free software; you can redistribute it and/or modify it under 13 | # the terms of the MIT licence: 14 | # 15 | # Permission is hereby granted, free of charge, to any person obtaining a 16 | # copy of this software and associated documentation files (the "Software"), 17 | # to deal in the Software without restriction, including without limitation 18 | # the rights to use, copy, modify, merge, publish, distribute, sublicense, 19 | # and/or sell copies of the Software, and to permit persons to whom the 20 | # Software is furnished to do so, subject to the following conditions: 21 | # 22 | # The above copyright notice and this permission notice shall be included in 23 | # all copies or substantial portions of the Software. 24 | # 25 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 26 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 27 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 28 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 29 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 30 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 31 | # DEALINGS IN THE SOFTWARE. 32 | # 33 | 34 | from __future__ import division, unicode_literals, print_function, absolute_import 35 | 36 | import visa 37 | 38 | def test_itc4(): 39 | print("Test start") 40 | itc4 = visa.Instrument("COM2", term_chars=b"\r", timeout=5) 41 | itc4.write(b"V") 42 | print(itc4.read()) 43 | print("Test end") 44 | -------------------------------------------------------------------------------- /examples/keithley2000.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # 4 | # keithley2000.py - PyVISA test code for Keithley 2000 multimeter 5 | # 6 | # Copyright © 2005, 2006, 2007, 2008 7 | # Torsten Bronger , 8 | # Gregor Thalhammer . 9 | # 10 | # This file is part of PyVISA. 11 | # 12 | # PyVISA is free software; you can redistribute it and/or modify it under 13 | # the terms of the MIT licence: 14 | # 15 | # Permission is hereby granted, free of charge, to any person obtaining a 16 | # copy of this software and associated documentation files (the "Software"), 17 | # to deal in the Software without restriction, including without limitation 18 | # the rights to use, copy, modify, merge, publish, distribute, sublicense, 19 | # and/or sell copies of the Software, and to permit persons to whom the 20 | # Software is furnished to do so, subject to the following conditions: 21 | # 22 | # The above copyright notice and this permission notice shall be included in 23 | # all copies or substantial portions of the Software. 24 | # 25 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 26 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 27 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 28 | # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 29 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 30 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 31 | # DEALINGS IN THE SOFTWARE. 32 | # 33 | 34 | from __future__ import division, unicode_literals, print_function, absolute_import 35 | 36 | import visa 37 | 38 | def test_keithley2000(monkeypatch): 39 | monkeypatch.setattr(visa.GpibInstrument, 'interface_type', VI_INTF_GPIB) 40 | monkeypatch.setattr(visa.GpibInstrument, 'stb', 0x40) 41 | print("Test start") 42 | keithley = visa.GpibInstrument(12) 43 | milliseconds = 500 44 | number_of_values = 10 45 | keithley.write(("F0B2M2G0T2Q%dI%dX" % (milliseconds, number_of_values)).encode('ascii')) 46 | keithley.trigger() 47 | keithley.wait_for_srq() 48 | voltages = keithley.read_floats() 49 | if voltages: 50 | print("Average: ", sum(voltages) / len(voltages)) 51 | print("Test end") 52 | -------------------------------------------------------------------------------- /pyvisa/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pyvisa 4 | ~~~~~~ 5 | 6 | Python wrapper of National Instrument (NI) Virtual Instruments Software 7 | Architecture library (VISA). 8 | 9 | This file is part of PyVISA. 10 | 11 | :copyright: 2014 by PyVISA Authors, see AUTHORS for more details. 12 | :license: MIT, see LICENSE for more details. 13 | """ 14 | 15 | from __future__ import division, unicode_literals, print_function, absolute_import 16 | 17 | import logging 18 | import pkg_resources 19 | 20 | from . import compat 21 | logger = logging.getLogger('pyvisa') 22 | logger.addHandler(compat.NullHandler()) 23 | 24 | 25 | def log_to_screen(level=logging.DEBUG): 26 | log_to_stream(None, level) # sys.stderr by default 27 | 28 | def log_to_stream(stream_output, level=logging.DEBUG): 29 | logger.setLevel(level) 30 | ch = logging.StreamHandler(stream_output) 31 | ch.setLevel(level) 32 | 33 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 34 | 35 | ch.setFormatter(formatter) 36 | 37 | logger.addHandler(ch) 38 | 39 | 40 | __version__ = "unknown" 41 | try: # pragma: no cover 42 | __version__ = pkg_resources.get_distribution('pyvisa').version 43 | except: # pragma: no cover 44 | pass # we seem to have a local copy without any repository control or installed without setuptools 45 | # so the reported version will be __unknown__ 46 | 47 | 48 | from .highlevel import ResourceManager 49 | from .errors import (Error, VisaIOError, VisaIOWarning, VisaTypeError, 50 | UnknownHandler, OSNotSupported, InvalidBinaryFormat, 51 | InvalidSession, LibraryError) 52 | # This is needed to registry all resources. 53 | from .resources import Resource 54 | from . import ctwrapper 55 | -------------------------------------------------------------------------------- /pyvisa/compat/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pyvisa.compat 4 | ~~~~~~~~~~~~~ 5 | 6 | Compatibility layer. 7 | 8 | :copyright: 2014 by PyVISA Authors, see AUTHORS for more details. 9 | :license: BSD, see LICENSE for more details. 10 | """ 11 | 12 | from __future__ import (division, unicode_literals, print_function, 13 | absolute_import) 14 | 15 | import sys 16 | 17 | 18 | PYTHON3 = sys.version >= '3' 19 | 20 | if PYTHON3: 21 | string_types = str 22 | 23 | def u(x): 24 | return x 25 | 26 | integer_types = (int, ) 27 | 28 | input = input 29 | 30 | int_to_bytes = int.to_bytes 31 | int_from_bytes = int.from_bytes 32 | 33 | else: 34 | string_types = basestring 35 | 36 | import codecs 37 | 38 | def u(x): 39 | return codecs.unicode_escape_decode(x)[0] 40 | 41 | integer_types = (int, long) 42 | 43 | input = raw_input 44 | 45 | # The 2 following function implementation extracted from the python-future 46 | # project 47 | import collections 48 | 49 | def int_to_bytes(integer, length, byteorder, signed=False): 50 | """ 51 | Return an array of bytes representing an integer. 52 | The integer is represented using length bytes. An OverflowError is 53 | raised if the integer is not representable with the given number of 54 | bytes. 55 | The byteorder argument determines the byte order used to represent the 56 | integer. If byteorder is 'big', the most significant byte is at the 57 | beginning of the byte array. If byteorder is 'little', the most 58 | significant byte is at the end of the byte array. To request the 59 | native byte order of the host system, use `sys.byteorder' as the byte 60 | order value. 61 | The signed keyword-only argument determines whether two's complement is 62 | used to represent the integer. If signed is False and a negative 63 | integer is given, an OverflowError is raised. 64 | """ 65 | if length < 0: 66 | raise ValueError("length argument must be non-negative") 67 | if length == 0 and integer == 0: 68 | return bytes() 69 | if signed and integer < 0: 70 | bits = length * 8 71 | num = (2**bits) + integer 72 | if num <= 0: 73 | raise OverflowError("int too smal to convert") 74 | else: 75 | if integer < 0: 76 | raise OverflowError("can't convert negative int to unsigned") 77 | num = integer 78 | if byteorder not in ('little', 'big'): 79 | raise ValueError("byteorder must be either 'little' or 'big'") 80 | h = b'%x' % num 81 | s = bytes((b'0'*(len(h) % 2) + h).zfill(length*2).decode('hex')) 82 | if signed: 83 | high_set = s[0] & 0x80 84 | if integer > 0 and high_set: 85 | raise OverflowError("int too big to convert") 86 | if integer < 0 and not high_set: 87 | raise OverflowError("int too small to convert") 88 | if len(s) > length: 89 | raise OverflowError("int too big to convert") 90 | return s if byteorder == 'big' else s[::-1] 91 | 92 | def int_from_bytes(mybytes, byteorder='big', signed=False): 93 | """ 94 | Return the integer represented by the given array of bytes. 95 | The mybytes argument must either support the buffer protocol or be an 96 | iterable object producing bytes. Bytes and bytearray are examples of 97 | built-in objects that support the buffer protocol. 98 | The byteorder argument determines the byte order used to represent the 99 | integer. If byteorder is 'big', the most significant byte is at the 100 | beginning of the byte array. If byteorder is 'little', the most 101 | significant byte is at the end of the byte array. To request the 102 | native byte order of the host system, use `sys.byteorder' as the byte 103 | order value. 104 | The signed keyword-only argument indicates whether two's complement is 105 | used to represent the integer. 106 | """ 107 | if byteorder not in ('little', 'big'): 108 | raise ValueError("byteorder must be either 'little' or 'big'") 109 | if isinstance(mybytes, unicode): 110 | raise TypeError("cannot convert unicode objects to bytes") 111 | # mybytes can also be passed as a sequence of integers on Py3. 112 | # Test for this: 113 | elif isinstance(mybytes, collections.Iterable): 114 | mybytes = bytes(mybytes) 115 | b = mybytes if byteorder == 'big' else mybytes[::-1] 116 | if len(b) == 0: 117 | b = b'\x00' 118 | # The encode() method has been disabled by newbytes, but Py2's 119 | # str has it: 120 | num = int(b.encode('hex'), 16) 121 | if signed and (b[0] & 0x80): 122 | num = num - (2 ** (len(b)*8)) 123 | return num 124 | 125 | try: 126 | from collections import OrderedDict 127 | except ImportError: 128 | from .ordereddict import OrderedDict 129 | 130 | try: 131 | from logging import NullHandler 132 | except ImportError: 133 | from .nullhandler import NullHandler 134 | 135 | 136 | def with_metaclass(meta, *bases): 137 | """Create a base class with a metaclass.""" 138 | # This requires a bit of explanation: the basic idea is to make a dummy 139 | # metaclass for one level of class instantiation that replaces itself with 140 | # the actual metaclass. 141 | class metaclass(meta): 142 | def __new__(cls, name, this_bases, d): 143 | return meta(name, bases, d) 144 | return type.__new__(metaclass, str('temporary_class'), (), {}) 145 | -------------------------------------------------------------------------------- /pyvisa/compat/nullhandler.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pyvisa.compat.nullhandler 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Taken from the Python 2.7 source code. 7 | 8 | :copyright: 2013, PSF 9 | :license: PSF License 10 | """ 11 | 12 | from __future__ import division, unicode_literals, print_function, absolute_import 13 | 14 | import logging 15 | 16 | 17 | class NullHandler(logging.Handler): 18 | """ 19 | This handler does nothing. It's intended to be used to avoid the 20 | "No handlers could be found for logger XXX" one-off warning. This is 21 | important for library code, which may contain code to log events. If a user 22 | of the library does not configure logging, the one-off warning might be 23 | produced; to avoid this, the library developer simply needs to instantiate 24 | a NullHandler and add it to the top-level logger of the library module or 25 | package. 26 | """ 27 | def handle(self, record): 28 | pass 29 | 30 | def emit(self, record): 31 | pass 32 | 33 | def createLock(self): 34 | # noinspection PyAttributeOutsideInit 35 | self.lock = None 36 | -------------------------------------------------------------------------------- /pyvisa/compat/ordereddict.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2009 Raymond Hettinger 2 | # 3 | # Permission is hereby granted, free of charge, to any person 4 | # obtaining a copy of this software and associated documentation files 5 | # (the "Software"), to deal in the Software without restriction, 6 | # including without limitation the rights to use, copy, modify, merge, 7 | # publish, distribute, sublicense, and/or sell copies of the Software, 8 | # and to permit persons to whom the Software is furnished to do so, 9 | # subject to the following conditions: 10 | # 11 | # The above copyright notice and this permission notice shall be 12 | # included in all copies or substantial portions of the Software. 13 | # 14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 16 | # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 18 | # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 19 | # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 20 | # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 21 | # OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | from UserDict import DictMixin 24 | 25 | class OrderedDict(dict, DictMixin): 26 | 27 | def __init__(self, *args, **kwds): 28 | if len(args) > 1: 29 | raise TypeError('expected at most 1 arguments, got %d' % len(args)) 30 | try: 31 | self.__end 32 | except AttributeError: 33 | self.clear() 34 | self.update(*args, **kwds) 35 | 36 | def clear(self): 37 | self.__end = end = [] 38 | end += [None, end, end] # sentinel node for doubly linked list 39 | self.__map = {} # key --> [key, prev, next] 40 | dict.clear(self) 41 | 42 | def __setitem__(self, key, value): 43 | if key not in self: 44 | end = self.__end 45 | curr = end[1] 46 | curr[2] = end[1] = self.__map[key] = [key, curr, end] 47 | dict.__setitem__(self, key, value) 48 | 49 | def __delitem__(self, key): 50 | dict.__delitem__(self, key) 51 | key, prev, next = self.__map.pop(key) 52 | prev[2] = next 53 | next[1] = prev 54 | 55 | def __iter__(self): 56 | end = self.__end 57 | curr = end[2] 58 | while curr is not end: 59 | yield curr[0] 60 | curr = curr[2] 61 | 62 | def __reversed__(self): 63 | end = self.__end 64 | curr = end[1] 65 | while curr is not end: 66 | yield curr[0] 67 | curr = curr[1] 68 | 69 | def popitem(self, last=True): 70 | if not self: 71 | raise KeyError('dictionary is empty') 72 | if last: 73 | key = reversed(self).next() 74 | else: 75 | key = iter(self).next() 76 | value = self.pop(key) 77 | return key, value 78 | 79 | def __reduce__(self): 80 | items = [[k, self[k]] for k in self] 81 | tmp = self.__map, self.__end 82 | del self.__map, self.__end 83 | inst_dict = vars(self).copy() 84 | self.__map, self.__end = tmp 85 | if inst_dict: 86 | return (self.__class__, (items,), inst_dict) 87 | return self.__class__, (items,) 88 | 89 | def keys(self): 90 | return list(self) 91 | 92 | setdefault = DictMixin.setdefault 93 | update = DictMixin.update 94 | pop = DictMixin.pop 95 | values = DictMixin.values 96 | items = DictMixin.items 97 | iterkeys = DictMixin.iterkeys 98 | itervalues = DictMixin.itervalues 99 | iteritems = DictMixin.iteritems 100 | 101 | def __repr__(self): 102 | if not self: 103 | return '%s()' % (self.__class__.__name__,) 104 | return '%s(%r)' % (self.__class__.__name__, self.items()) 105 | 106 | def copy(self): 107 | return self.__class__(self) 108 | 109 | @classmethod 110 | def fromkeys(cls, iterable, value=None): 111 | d = cls() 112 | for key in iterable: 113 | d[key] = value 114 | return d 115 | 116 | def __eq__(self, other): 117 | if isinstance(other, OrderedDict): 118 | if len(self) != len(other): 119 | return False 120 | for p, q in zip(self.items(), other.items()): 121 | if p != q: 122 | return False 123 | return True 124 | return dict.__eq__(self, other) 125 | 126 | def __ne__(self, other): 127 | return not self == other 128 | -------------------------------------------------------------------------------- /pyvisa/compat/struct.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pyvisa.compat.struct 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Python 2/3 compatibility for struct module 7 | 8 | :copyright: 2015, PSF 9 | :license: PSF License 10 | """ 11 | 12 | from __future__ import (division, unicode_literals, print_function, 13 | absolute_import) 14 | 15 | import sys 16 | import struct 17 | 18 | # we always want the exception to be able to catch it 19 | error = struct.error 20 | 21 | # compatibility for unicode literals was introduced in 2.7.8 22 | # if we're above that there is nothing to do except aliasing 23 | if sys.hexversion >= 0x02070800: 24 | pack = struct.pack 25 | pack_into = struct.pack_into 26 | unpack = struct.unpack 27 | unpack_from = struct.unpack_from 28 | calcsize = struct.calcsize 29 | else: 30 | def pack(fmt, *args): 31 | return struct.pack(str(fmt), *args) 32 | 33 | def pack_into(fmt, *args, **argk): 34 | return struct.pack_into(str(fmt), *args, **argk) 35 | 36 | def unpack(fmt, string): 37 | return struct.unpack(str(fmt), string) 38 | 39 | def unpack_from(fmt, *args, **kwargs): 40 | return struct.unpack_from(str(fmt), *args, **kwargs) 41 | 42 | def calcsize(fmt): 43 | return struct.calcsize(str(fmt)) 44 | -------------------------------------------------------------------------------- /pyvisa/ctwrapper/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pyvisa.ctwrapper 4 | ~~~~~~~~~~~~~~~~ 5 | 6 | ctypes wrapper for NI-VISA library. 7 | 8 | This file is part of PyVISA. 9 | 10 | :copyright: 2014 by PyVISA Authors, see AUTHORS for more details. 11 | :license: MIT, see LICENSE for more details. 12 | """ 13 | 14 | from __future__ import division, unicode_literals, print_function, absolute_import 15 | 16 | from .highlevel import NIVisaLibrary 17 | 18 | WRAPPER_CLASS = NIVisaLibrary 19 | 20 | -------------------------------------------------------------------------------- /pyvisa/ctwrapper/cthelper.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pyvisa.ctwrapper._ct 4 | ~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Cross platform helper of ctypes. 7 | 8 | This file is part of PyVISA. 9 | 10 | :copyright: 2014 by PyVISA Authors, see AUTHORS for more details. 11 | :license: MIT, see LICENSE for more details. 12 | """ 13 | 14 | from __future__ import division, unicode_literals, print_function, absolute_import 15 | 16 | # ctypes and os shouldn't be re-exported. 17 | import os as _os 18 | import sys as _sys 19 | 20 | import ctypes as _ctypes 21 | 22 | PYTHON3 = _sys.version_info >= (3, 0) 23 | 24 | if _os.name == 'nt': 25 | FUNCTYPE, Library = _ctypes.WINFUNCTYPE, _ctypes.WinDLL 26 | else: 27 | FUNCTYPE, Library = _ctypes.CFUNCTYPE, _ctypes.CDLL 28 | 29 | # On Linux, find Library returns the name not the path. 30 | # This excerpt provides a modified find_library. 31 | # noinspection PyUnresolvedReferences 32 | if _os.name == "posix" and _sys.platform.startswith('linux'): 33 | 34 | # Andreas Degert's find functions, using gcc, /sbin/ldconfig, objdump 35 | def define_find_libary(): 36 | import re 37 | import tempfile 38 | import errno 39 | 40 | def _findlib_gcc(name): 41 | expr = r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name) 42 | fdout, ccout = tempfile.mkstemp() 43 | _os.close(fdout) 44 | cmd = 'if type gcc >/dev/null 2>&1; then CC=gcc; else CC=cc; fi;' \ 45 | '$CC -Wl,-t -o ' + ccout + ' 2>&1 -l' + name 46 | trace = '' 47 | try: 48 | f = _os.popen(cmd) 49 | trace = f.read() 50 | f.close() 51 | finally: 52 | try: 53 | _os.unlink(ccout) 54 | except OSError as e: 55 | if e.errno != errno.ENOENT: 56 | raise 57 | res = re.search(expr, trace) 58 | if not res: 59 | return None 60 | return res.group(0) 61 | 62 | def _findlib_ldconfig(name): 63 | # XXX assuming GLIBC's ldconfig (with option -p) 64 | expr = r'/[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name) 65 | with _os.popen('/sbin/ldconfig -p 2>/dev/null') as pipe: 66 | res = re.search(expr, pipe.read()) 67 | if not res: 68 | # Hm, this works only for libs needed by the python executable. 69 | cmd = 'ldd %s 2>/dev/null' % _sys.executable 70 | with _os.popen(cmd) as pipe: 71 | res = re.search(expr, pipe.read()) 72 | if not res: 73 | return None 74 | return res.group(0) 75 | 76 | def _find_library(name): 77 | path = _findlib_ldconfig(name) or _findlib_gcc(name) 78 | if path: 79 | return _os.path.realpath(path) 80 | return path 81 | 82 | return _find_library 83 | 84 | find_library = define_find_libary() 85 | else: 86 | from ctypes.util import find_library 87 | -------------------------------------------------------------------------------- /pyvisa/ctwrapper/highlevel.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pyvisa.ctwrapper.highlevel 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Highlevel wrapper of the VISA Library. 7 | 8 | This file is part of PyVISA. 9 | 10 | :copyright: 2014 by PyVISA Authors, see AUTHORS for more details. 11 | :license: MIT, see LICENSE for more details. 12 | """ 13 | 14 | from __future__ import division, unicode_literals, print_function, absolute_import 15 | 16 | import logging 17 | import warnings 18 | 19 | from pyvisa import constants, errors, highlevel, logger 20 | from pyvisa.compat import integer_types, OrderedDict 21 | 22 | from .cthelper import Library, find_library 23 | from . import functions 24 | 25 | 26 | logger = logging.LoggerAdapter(logger, {'backend': 'ni'}) 27 | 28 | 29 | def add_visa_methods(aclass): 30 | for method in functions.visa_functions: 31 | setattr(aclass, method, getattr(functions, method)) 32 | return aclass 33 | 34 | 35 | def _args_to_str(args): 36 | out = [] 37 | for arg in args: 38 | try: 39 | # noinspection PyProtectedMember 40 | out.append(str(arg._obj)) 41 | except AttributeError: 42 | out.append(arg) 43 | return tuple(out) 44 | 45 | 46 | def unique(seq): 47 | """Keep unique while preserving order. 48 | """ 49 | seen = set() 50 | return [x for x in seq if not (x in seen or seen.add(x))] 51 | 52 | 53 | @add_visa_methods 54 | class NIVisaLibrary(highlevel.VisaLibraryBase): 55 | """High level NI-VISA Library wrapper using ctypes. 56 | 57 | The easiest way to instantiate the library is to let `pyvisa` find the 58 | right one for you. This looks first in your configuration file (~/.pyvisarc). 59 | If it fails, it uses `ctypes.util.find_library` to try to locate a library 60 | in a way similar to what the compiler does: 61 | 62 | >>> visa_library = NIVisaLibrary() 63 | 64 | But you can also specify the path: 65 | 66 | >>> visa_library = NIVisaLibrary('/my/path/visa.so') 67 | 68 | :param library_path: path of the VISA library. 69 | """ 70 | 71 | @staticmethod 72 | def get_library_paths(): 73 | """Return a tuple of possible library paths. 74 | 75 | :rtype: tuple 76 | """ 77 | 78 | from ..util import LibraryPath, read_user_library_path 79 | 80 | # Try to find NI libraries using known names. 81 | tmp = [find_library(library_path) 82 | for library_path in ('visa', 'visa32', 'visa32.dll', 'visa64', 'visa64.dll')] 83 | 84 | logger.debug('Automatically found library files: %s' % tmp) 85 | 86 | # Prepend the path provided by the user in configuration files (if any). 87 | user_lib = read_user_library_path() 88 | if user_lib: 89 | tmp.insert(0, user_lib) 90 | 91 | # Deduplicate and convert string paths to LibraryPath objects 92 | tmp = [LibraryPath(library_path) 93 | for library_path in unique(tmp) 94 | if library_path is not None] 95 | 96 | return tuple(tmp) 97 | 98 | @staticmethod 99 | def get_debug_info(): 100 | """Return a list of lines with backend info. 101 | """ 102 | from pyvisa import __version__ 103 | d = OrderedDict() 104 | d['Version'] = '%s (bundled with PyVISA)' % __version__ 105 | 106 | paths = NIVisaLibrary.get_library_paths() 107 | 108 | for ndx, visalib in enumerate(paths, 1): 109 | nfo = OrderedDict() 110 | nfo['found by'] = visalib.found_by 111 | nfo['bitness'] = visalib.bitness 112 | try: 113 | lib = NIVisaLibrary(visalib) 114 | sess, _ = lib.open_default_resource_manager() 115 | nfo['Vendor'] = str(lib.get_attribute(sess, constants.VI_ATTR_RSRC_MANF_NAME)[0]) 116 | nfo['Impl. Version'] = str(lib.get_attribute(sess, constants.VI_ATTR_RSRC_IMPL_VERSION)[0]) 117 | nfo['Spec. Version'] = str(lib.get_attribute(sess, constants.VI_ATTR_RSRC_SPEC_VERSION)[0]) 118 | lib.close(sess) 119 | except Exception as e: 120 | e = str(e) 121 | if 'No matching architecture' in e: 122 | nfo['Could not get more info'] = 'Interpreter and library have different bitness.' 123 | else: 124 | nfo['Could not get more info'] = str(e).split('\n') 125 | 126 | d['#%d: %s' % (ndx, visalib)] = nfo 127 | 128 | if not paths: 129 | d['Binary library'] = 'Not found' 130 | 131 | return d 132 | 133 | def _init(self): 134 | try: 135 | lib = Library(self.library_path) 136 | except OSError as exc: 137 | raise errors.LibraryError.from_exception(exc, self.library_path) 138 | 139 | self.lib = lib 140 | 141 | # Set the argtypes, restype and errcheck for each function 142 | # of the visa library. Additionally store in `_functions` the 143 | # name of the functions. 144 | functions.set_signatures(self.lib, errcheck=self._return_handler) 145 | 146 | logger.debug('Library signatures: %d ok, %d failed', 147 | len(getattr(self.lib, '_functions', [])), 148 | len(getattr(self.lib, '_functions_failed', []))) 149 | 150 | # Set the library functions as attributes of the object. 151 | for method_name in getattr(self.lib, '_functions', []): 152 | setattr(self, method_name, getattr(self.lib, method_name)) 153 | 154 | def _return_handler(self, ret_value, func, arguments): 155 | """Check return values for errors and warnings. 156 | """ 157 | 158 | logger.debug('%s%s -> %r', 159 | func.__name__, _args_to_str(arguments), ret_value, 160 | extra=self._logging_extra) 161 | 162 | try: 163 | ret_value = constants.StatusCode(ret_value) 164 | except ValueError: 165 | pass 166 | 167 | self._last_status = ret_value 168 | 169 | # The first argument of almost all registered visa functions is a session. 170 | # We store the error code per session 171 | session = None 172 | if func.__name__ not in ('viFindNext', ): 173 | try: 174 | session = arguments[0] 175 | except KeyError: 176 | raise Exception('Function %r does not seem to be a valid ' 177 | 'visa function (len args %d)' % (func, len(arguments))) 178 | 179 | # Functions that use the first parameter to get a session value. 180 | if func.__name__ in ('viOpenDefaultRM', ): 181 | # noinspection PyProtectedMember 182 | session = session._obj.value 183 | 184 | if isinstance(session, integer_types): 185 | self._last_status_in_session[session] = ret_value 186 | else: 187 | # Functions that might or might have a session in the first argument. 188 | if func.__name__ not in ('viClose', 'viGetAttribute', 'viSetAttribute', 'viStatusDesc'): 189 | raise Exception('Function %r does not seem to be a valid ' 190 | 'visa function (type args[0] %r)' % (func, type(session))) 191 | 192 | if ret_value < 0: 193 | raise errors.VisaIOError(ret_value) 194 | 195 | if ret_value in self.issue_warning_on: 196 | if session and ret_value not in self._ignore_warning_in_session[session]: 197 | warnings.warn(errors.VisaIOWarning(ret_value), stacklevel=2) 198 | 199 | return ret_value 200 | 201 | def list_resources(self, session, query='?*::INSTR'): 202 | """Returns a tuple of all connected devices matching query. 203 | 204 | note: The query uses the VISA Resource Regular Expression syntax - which is not the same 205 | as the Python regular expression syntax. (see below) 206 | 207 | The VISA Resource Regular Expression syntax is defined in the VISA Library specification: 208 | http://www.ivifoundation.org/docs/vpp43.pdf 209 | 210 | Symbol Meaning 211 | ---------- ---------- 212 | 213 | ? Matches any one character. 214 | 215 | \ Makes the character that follows it an ordinary character 216 | instead of special character. For example, when a question 217 | mark follows a backslash (\?), it matches the ? character 218 | instead of any one character. 219 | 220 | [list] Matches any one character from the enclosed list. You can 221 | use a hyphen to match a range of characters. 222 | 223 | [^list] Matches any character not in the enclosed list. You can use 224 | a hyphen to match a range of characters. 225 | 226 | * Matches 0 or more occurrences of the preceding character or 227 | expression. 228 | 229 | + Matches 1 or more occurrences of the preceding character or 230 | expression. 231 | 232 | Exp|exp Matches either the preceding or following expression. The or 233 | operator | matches the entire expression that precedes or 234 | follows it and not just the character that precedes or follows 235 | it. For example, VXI|GPIB means (VXI)|(GPIB), not VX(I|G)PIB. 236 | 237 | (exp) Grouping characters or expressions. 238 | 239 | Thus the default query, '?*::INSTR', matches any sequences of characters ending 240 | ending with '::INSTR'. 241 | 242 | :param query: a VISA Resource Regular Expression used to match devices. 243 | """ 244 | 245 | resources = [] 246 | 247 | try: 248 | find_list, return_counter, instrument_description, err = self.find_resources(session, query) 249 | except errors.VisaIOError as e: 250 | if e.error_code == constants.StatusCode.error_resource_not_found: 251 | return tuple() 252 | raise e 253 | 254 | resources.append(instrument_description) 255 | for i in range(return_counter - 1): 256 | resources.append(self.find_next(find_list)[0]) 257 | 258 | self.close(find_list) 259 | 260 | return tuple(resource for resource in resources) 261 | 262 | -------------------------------------------------------------------------------- /pyvisa/ctwrapper/types.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pyvisa.ctwrapper.types 4 | ~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | VISA VPP-4.3 data types (VPP-4.3.2 spec, section 3) using ctypes constants. 7 | 8 | This file is part of PyVISA. 9 | 10 | All data types that are defined by VPP-4.3.2. 11 | 12 | The module exports all data types including the pointer and array types. This 13 | means "ViUInt32" and such. 14 | 15 | :copyright: 2014 by PyVISA Authors, see AUTHORS for more details. 16 | :license: MIT, see LICENSE for more details. 17 | """ 18 | 19 | from __future__ import division, unicode_literals, print_function, absolute_import 20 | 21 | import ctypes as _ctypes 22 | 23 | from .cthelper import PYTHON3, FUNCTYPE 24 | 25 | # Part One: Type Assignments for VISA and Instrument Drivers, see spec table 26 | # 3.1.1. 27 | # 28 | # Remark: The pointer and probably also the array variants are of no 29 | # significance in Python because there is no native call-by-reference. 30 | # However, as long as I'm not fully sure about this, they won't hurt. 31 | 32 | def _type_pair(ctypes_type): 33 | return ctypes_type, _ctypes.POINTER(ctypes_type) 34 | 35 | 36 | def _type_triplet(ctypes_type): 37 | return _type_pair(ctypes_type) + (_ctypes.POINTER(ctypes_type),) 38 | 39 | ViUInt64, ViPUInt64, ViAUInt64 = _type_triplet(_ctypes.c_uint64) 40 | ViInt64, ViPInt64, ViAInt64 = _type_triplet(_ctypes.c_int64) 41 | ViUInt32, ViPUInt32, ViAUInt32 = _type_triplet(_ctypes.c_uint32) 42 | ViInt32, ViPInt32, ViAInt32 = _type_triplet(_ctypes.c_int32) 43 | ViUInt16, ViPUInt16, ViAUInt16 = _type_triplet(_ctypes.c_ushort) 44 | ViInt16, ViPInt16, ViAInt16 = _type_triplet(_ctypes.c_short) 45 | ViUInt8, ViPUInt8, ViAUInt8 = _type_triplet(_ctypes.c_ubyte) 46 | ViInt8, ViPInt8, ViAInt8 = _type_triplet(_ctypes.c_byte) 47 | ViAddr, ViPAddr, ViAAddr = _type_triplet(_ctypes.c_void_p) 48 | ViChar, ViPChar, ViAChar = _type_triplet(_ctypes.c_char) 49 | ViByte, ViPByte, ViAByte = _type_triplet(_ctypes.c_ubyte) 50 | ViBoolean, ViPBoolean, ViABoolean = _type_triplet(ViUInt16) 51 | ViReal32, ViPReal32, ViAReal32 = _type_triplet(_ctypes.c_float) 52 | ViReal64, ViPReal64, ViAReal64 = _type_triplet(_ctypes.c_double) 53 | 54 | 55 | if PYTHON3: 56 | class ViString(object): 57 | 58 | @classmethod 59 | def from_param(cls, obj): 60 | if isinstance(obj, str): 61 | return bytes(obj, 'ascii') 62 | return obj 63 | 64 | class ViAString(object): 65 | 66 | @classmethod 67 | def from_param(cls, obj): 68 | return _ctypes.POINTER(obj) 69 | 70 | ViPString = ViString 71 | 72 | else: 73 | 74 | class ViString(object): 75 | 76 | @classmethod 77 | def from_param(cls, obj): 78 | if isinstance(obj, str): 79 | return obj 80 | elif isinstance(obj, unicode): 81 | return obj.encode('ascii') 82 | return obj 83 | 84 | class ViAString(object): 85 | 86 | @classmethod 87 | def from_param(cls, obj): 88 | return _ctypes.POINTER(obj) 89 | 90 | ViPString = ViString 91 | 92 | # This follows visa.h definition, but involves a lot of manual conversion. 93 | # ViBuf, ViPBuf, ViABuf = ViPByte, ViPByte, _ctypes.POINTER(ViPByte) 94 | 95 | ViBuf, ViPBuf, ViABuf = ViPString, ViPString, ViAString 96 | 97 | 98 | def buffer_to_text(buf): 99 | return buf.value.decode('ascii') 100 | 101 | 102 | ViRsrc = ViString 103 | ViPRsrc = ViString 104 | ViARsrc = ViAString 105 | 106 | ViKeyId, ViPKeyId = ViString, ViPString 107 | 108 | ViStatus, ViPStatus, ViAStatus = _type_triplet(ViInt32) 109 | ViVersion, ViPVersion, ViAVersion = _type_triplet(ViUInt32) 110 | _ViObject, ViPObject, ViAObject = _type_triplet(ViUInt32) 111 | _ViSession, ViPSession, ViASession = _type_triplet(ViUInt32) 112 | 113 | 114 | class ViObject(_ViObject): 115 | 116 | @classmethod 117 | def from_param(cls, obj): 118 | if obj is None: 119 | raise ValueError('Session cannot be None. The resource might be closed.') 120 | return _ViObject.from_param(obj) 121 | 122 | 123 | ViSession = ViObject 124 | 125 | 126 | ViAttr = ViUInt32 127 | ViConstString = _ctypes.POINTER(ViChar) 128 | 129 | 130 | # Part Two: Type Assignments for VISA only, see spec table 3.1.2. The 131 | # difference to the above is of no significance in Python, so I use it here 132 | # only for easier synchronisation with the spec. 133 | 134 | ViAccessMode, ViPAccessMode = _type_pair(ViUInt32) 135 | ViBusAddress, ViPBusAddress = _type_pair(ViUInt32) 136 | ViBusAddress64, ViPBusAddress64 = _type_pair(ViUInt64) 137 | 138 | ViBusSize = ViUInt32 139 | 140 | ViAttrState, ViPAttrState = _type_pair(ViUInt32) 141 | 142 | # The following is weird, taken from news:zn2ek2w2.fsf@python.net 143 | ViVAList = _ctypes.POINTER(_ctypes.c_char) 144 | 145 | ViEventType, ViPEventType, ViAEventType = _type_triplet(ViUInt32) 146 | 147 | ViPAttr = _ctypes.POINTER(ViAttr) 148 | ViAAttr = ViPAttr 149 | 150 | ViEventFilter = ViUInt32 151 | 152 | ViFindList, ViPFindList = _type_pair(ViObject) 153 | ViEvent, ViPEvent = _type_pair(ViObject) 154 | ViJobId, ViPJobId = _type_pair(ViUInt32) 155 | 156 | # Class of callback functions for event handling, first type is result type 157 | ViHndlr = FUNCTYPE(ViStatus, ViSession, ViEventType, ViEvent, ViAddr) 158 | -------------------------------------------------------------------------------- /pyvisa/resources/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pyvisa.resources 4 | ~~~~~~~~~~~~~~~~ 5 | 6 | High level wrappers for resources. 7 | 8 | This file is part of PyVISA. 9 | 10 | :copyright: 2014 by PyVISA Authors, see AUTHORS for more details. 11 | :license: MIT, see LICENSE for more details. 12 | """ 13 | 14 | from __future__ import division, unicode_literals, print_function, absolute_import 15 | 16 | from .resource import Resource 17 | 18 | from .gpib import GPIBInterface 19 | from .vxi import VXIBackplane 20 | from .vxi import VXIInstrument 21 | 22 | from .messagebased import MessageBasedResource 23 | from .gpib import GPIBInstrument 24 | from .tcpip import TCPIPInstrument 25 | from .tcpip import TCPIPSocket 26 | from .serial import SerialInstrument 27 | from .usb import USBRaw 28 | from .usb import USBInstrument 29 | 30 | from .registerbased import RegisterBasedResource 31 | from .firewire import FirewireInstrument 32 | from .pxi import PXIMemory 33 | from .pxi import PXIInstrument 34 | from .vxi import VXIMemory 35 | 36 | __all__ = ['Resource', 'MessageBasedResource', 'RegisterBasedResource', 37 | 'GPIBInterface', 'VXIBackplane', 'VXIInstrument', 38 | 'GPIBInstrument', 'TCPIPInstrument', 'TCPIPSocket', 'SerialInstrument', 'USBRaw', 'USBInstrument', 39 | 'FirewireInstrument', 'PXIMemory', 'PXIInstrument', 'VXIMemory'] 40 | -------------------------------------------------------------------------------- /pyvisa/resources/firewire.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pyvisa.resources.vxi 4 | ~~~~~~~~~~~~~~~~~~~~ 5 | 6 | High level wrapper for VXI resources. 7 | 8 | This file is part of PyVISA. 9 | 10 | :copyright: 2014 by PyVISA Authors, see AUTHORS for more details. 11 | :license: MIT, see LICENSE for more details. 12 | """ 13 | 14 | from __future__ import division, unicode_literals, print_function, absolute_import 15 | 16 | from .. import constants 17 | 18 | from .registerbased import RegisterBasedResource 19 | 20 | 21 | @RegisterBasedResource.register(constants.InterfaceType.firewire, 'INSTR') 22 | class FirewireInstrument(RegisterBasedResource): 23 | """Communicates with to devices of type VXI::VXI logical address[::INSTR] 24 | 25 | More complex resource names can be specified with the following grammar: 26 | VXI[board]::VXI logical address[::INSTR] 27 | 28 | Do not instantiate directly, use :meth:`pyvisa.highlevel.ResourceManager.open_resource`. 29 | """ 30 | -------------------------------------------------------------------------------- /pyvisa/resources/gpib.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pyvisa.resources.gpib 4 | ~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | High level wrapper for GPIB resources. 7 | 8 | This file is part of PyVISA. 9 | 10 | :copyright: 2014 by PyVISA Authors, see AUTHORS for more details. 11 | :license: MIT, see LICENSE for more details. 12 | """ 13 | 14 | from __future__ import division, unicode_literals, print_function, absolute_import 15 | 16 | import time 17 | 18 | from .. import constants 19 | from .resource import Resource 20 | from .messagebased import MessageBasedResource, ControlRenMixin 21 | 22 | 23 | class _GPIBMixin(ControlRenMixin): 24 | """Common attributes and methods of GPIB Instr and Interface. 25 | """ 26 | 27 | def send_command(self, data): 28 | """Write GPIB command bytes on the bus. 29 | 30 | Corresponds to viGpibCommand function of the VISA library. 31 | 32 | :param data: data tor write. 33 | :type data: bytes 34 | :return: Number of written bytes, return value of the library call. 35 | :rtype: int, VISAStatus 36 | """ 37 | return self.visalib.gpib_command(self.session, data) 38 | 39 | def control_atn(self, mode): 40 | """Specifies the state of the ATN line and the local active controller state. 41 | 42 | Corresponds to viGpibControlATN function of the VISA library. 43 | 44 | :param mode: Specifies the state of the ATN line and optionally the local active controller state. 45 | (Constants.GPIB_ATN*) 46 | :return: return value of the library call. 47 | :rtype: VISAStatus 48 | """ 49 | return self.visalib.gpib_control_atn(self.session, mode) 50 | 51 | def pass_control(self, primary_address, secondary_address): 52 | """Tell the GPIB device at the specified address to become controller in charge (CIC). 53 | 54 | Corresponds to viGpibPassControl function of the VISA library. 55 | 56 | :param primary_address: Primary address of the GPIB device to which you want to pass control. 57 | :param secondary_address: Secondary address of the targeted GPIB device. 58 | If the targeted device does not have a secondary address, 59 | this parameter should contain the value Constants.NO_SEC_ADDR. 60 | :return: return value of the library call. 61 | :rtype: VISAStatus 62 | """ 63 | return self.visalib.gpib_pass_control(self.session, primary_address, secondary_address) 64 | 65 | def send_ifc(self): 66 | """Pulse the interface clear line (IFC) for at least 100 microseconds. 67 | 68 | Corresponds to viGpibSendIFC function of the VISA library. 69 | 70 | :return: return value of the library call. 71 | :rtype: VISAStatus 72 | """ 73 | return self.visalib.gpib_send_ifc(self.session) 74 | 75 | 76 | @Resource.register(constants.InterfaceType.gpib, 'INSTR') 77 | class GPIBInstrument(_GPIBMixin, MessageBasedResource): 78 | """Communicates with to devices of type GPIB::[::INSTR] 79 | 80 | More complex resource names can be specified with the following grammar: 81 | GPIB[board]::primary address[::secondary address][::INSTR] 82 | 83 | Do not instantiate directly, use :meth:`pyvisa.highlevel.ResourceManager.open_resource`. 84 | """ 85 | 86 | def wait_for_srq(self, timeout=25000): 87 | """Wait for a serial request (SRQ) coming from the instrument. 88 | 89 | Note that this method is not ended when *another* instrument signals an 90 | SRQ, only *this* instrument. 91 | 92 | :param timeout: the maximum waiting time in milliseconds. 93 | Defaul: 25000 (milliseconds). 94 | None means waiting forever if necessary. 95 | """ 96 | self.enable_event(constants.VI_EVENT_SERVICE_REQ, constants.VI_QUEUE) 97 | 98 | if timeout and not(0 <= timeout <= 4294967295): 99 | raise ValueError("timeout value is invalid") 100 | 101 | starting_time = time.clock() 102 | 103 | while True: 104 | if timeout is None: 105 | adjusted_timeout = constants.VI_TMO_INFINITE 106 | else: 107 | adjusted_timeout = int((starting_time + timeout/1e3 - time.clock())*1e3) 108 | if adjusted_timeout < 0: 109 | adjusted_timeout = 0 110 | 111 | self.wait_on_event(constants.VI_EVENT_SERVICE_REQ, adjusted_timeout) 112 | if self.stb & 0x40: 113 | break 114 | 115 | self.discard_events(constants.VI_EVENT_SERVICE_REQ, constants.VI_QUEUE) 116 | 117 | 118 | @Resource.register(constants.InterfaceType.gpib, 'INTFC') 119 | class GPIBInterface(_GPIBMixin, Resource): 120 | """Communicates with to devices of type GPIB::INTFC 121 | 122 | More complex resource names can be specified with the following grammar: 123 | GPIB[board]::INTFC 124 | 125 | Do not instantiate directly, use :meth:`pyvisa.highlevel.ResourceManager.open_resource`. 126 | """ 127 | 128 | def group_execute_trigger(self, *resources): 129 | 130 | for resource in resources: 131 | if not isinstance(resource, GPIBInstrument): 132 | raise ValueError('%r is not a GPIBInstrument', resource) 133 | 134 | # TODO: check that all resources are in the same board. 135 | 136 | if not self.is_controller_in_charge: 137 | self.send_ifc() 138 | 139 | command = [0x40, 0x20+31, ] # broadcast TAD#0 and "UNL" (don't listen) to all devices 140 | 141 | for resource in resources: 142 | # tell device GPIB::11 to listen 143 | command.append(0x20 + resource.primary_address) 144 | 145 | # send GET ('group execute trigger') 146 | command.append(0x08) 147 | 148 | return self.send_command(bytes(command)) 149 | -------------------------------------------------------------------------------- /pyvisa/resources/pxi.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pyvisa.resources.pxi 4 | ~~~~~~~~~~~~~~~~~~~~ 5 | 6 | High level wrapper for pxi resources. 7 | 8 | This file is part of PyVISA. 9 | 10 | :copyright: 2014 by PyVISA Authors, see AUTHORS for more details. 11 | :license: MIT, see LICENSE for more details. 12 | """ 13 | 14 | from __future__ import division, unicode_literals, print_function, absolute_import 15 | 16 | from .. import constants 17 | 18 | from .resource import Resource 19 | from .registerbased import RegisterBasedResource 20 | 21 | 22 | @Resource.register(constants.InterfaceType.pxi, 'INSTR') 23 | class PXIInstrument(RegisterBasedResource): 24 | """Communicates with to devices of type PXI::[::INSTR] 25 | 26 | More complex resource names can be specified with the following grammar: 27 | PXI[bus]::device[::function][::INSTR] 28 | or: 29 | PXI[interface]::bus-device[.function][::INSTR] 30 | or: 31 | PXI[interface]::CHASSISchassis number::SLOTslot number[::FUNCfunction][::INSTR] 32 | 33 | Do not instantiate directly, use :meth:`pyvisa.highlevel.ResourceManager.open_resource`. 34 | """ 35 | 36 | 37 | @Resource.register(constants.InterfaceType.pxi, 'MEMACC') 38 | class PXIMemory(RegisterBasedResource): 39 | """Communicates with to devices of type PXI[interface]::MEMACC 40 | 41 | Do not instantiate directly, use :meth:`pyvisa.highlevel.ResourceManager.open_resource`. 42 | """ 43 | -------------------------------------------------------------------------------- /pyvisa/resources/registerbased.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pyvisa.resources.registerbased 4 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | High level wrapper for RegisterBased Instruments. 7 | 8 | This file is part of PyVISA. 9 | 10 | :copyright: 2014 by PyVISA Authors, see AUTHORS for more details. 11 | :license: MIT, see LICENSE for more details. 12 | """ 13 | 14 | from __future__ import division, unicode_literals, print_function, absolute_import 15 | 16 | from .resource import Resource 17 | 18 | 19 | class RegisterBasedResource(Resource): 20 | """Base class for resources that use register based communication. 21 | """ 22 | 23 | def read_memory(self, space, offset, width, extended=False): 24 | """Reads in an 8-bit, 16-bit, 32-bit, or 64-bit value from the specified memory space and offset. 25 | 26 | :param space: Specifies the address space. (Constants.*SPACE*) 27 | :param offset: Offset (in bytes) of the address or register from which to read. 28 | :param width: Number of bits to read. 29 | :param extended: Use 64 bits offset independent of the platform. 30 | :return: Data read from memory. 31 | 32 | Corresponds to viIn* functions of the visa library. 33 | """ 34 | return self.visalib.read_memory(self.session, space, offset, width, extended) 35 | 36 | def write_memory(self, space, offset, data, width, extended=False): 37 | """Write in an 8-bit, 16-bit, 32-bit, value to the specified memory space and offset. 38 | 39 | :param space: Specifies the address space. (Constants.*SPACE*) 40 | :param offset: Offset (in bytes) of the address or register from which to read. 41 | :param data: Data to write to bus. 42 | :param width: Number of bits to read. 43 | :param extended: Use 64 bits offset independent of the platform. 44 | 45 | Corresponds to viOut* functions of the visa library. 46 | """ 47 | return self.visalib.write_memory(self.session, space, offset, data, width, extended) 48 | 49 | def move_in(self, space, offset, length, width, extended=False): 50 | """Moves a block of data to local memory from the specified address space and offset. 51 | 52 | :param space: Specifies the address space. (Constants.*SPACE*) 53 | :param offset: Offset (in bytes) of the address or register from which to read. 54 | :param length: Number of elements to transfer, where the data width of the elements to transfer 55 | is identical to the source data width. 56 | :param width: Number of bits to read per element. 57 | :param extended: Use 64 bits offset independent of the platform. 58 | """ 59 | return self.visalib.move_in(self.session, space, offset, length, width, extended) 60 | 61 | def move_out(self, space, offset, length, data, width, extended=False): 62 | """Moves a block of data from local memory to the specified address space and offset. 63 | 64 | :param space: Specifies the address space. (Constants.*SPACE*) 65 | :param offset: Offset (in bytes) of the address or register from which to read. 66 | :param length: Number of elements to transfer, where the data width of the elements to transfer 67 | is identical to the source data width. 68 | :param data: Data to write to bus. 69 | :param width: Number of bits to read per element. 70 | :param extended: Use 64 bits offset independent of the platform. 71 | """ 72 | return self.visalib.move_out(space, offset, length, data, width, extended) 73 | -------------------------------------------------------------------------------- /pyvisa/resources/serial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pyvisa.resources.serial 4 | ~~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | High level wrapper for Serial resources. 7 | 8 | This file is part of PyVISA. 9 | 10 | :copyright: 2014 by PyVISA Authors, see AUTHORS for more details. 11 | :license: MIT, see LICENSE for more details. 12 | """ 13 | 14 | from __future__ import division, unicode_literals, print_function, absolute_import 15 | 16 | from .. import constants 17 | 18 | from .messagebased import MessageBasedResource 19 | 20 | @MessageBasedResource.register(constants.InterfaceType.asrl, 'INSTR') 21 | class SerialInstrument(MessageBasedResource): 22 | """Communicates with devices of type ASRL[::INSTR] 23 | 24 | Do not instantiate directly, use :meth:`pyvisa.highlevel.ResourceManager.open_resource`. 25 | """ 26 | 27 | def flush(self, mask): 28 | """Manually clears the specified buffers and cause the buffer data 29 | to be written to the device. 30 | 31 | :param mask: Specifies the action to be taken with flushing the buffer. 32 | (Constants.READ*, .WRITE*, .IO*) 33 | """ 34 | self.visalib.flush(self.session, mask) 35 | -------------------------------------------------------------------------------- /pyvisa/resources/tcpip.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pyvisa.resources.tcpip 4 | ~~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | High level wrapper for TCPIP resources. 7 | 8 | This file is part of PyVISA. 9 | 10 | :copyright: 2014 by PyVISA Authors, see AUTHORS for more details. 11 | :license: MIT, see LICENSE for more details. 12 | """ 13 | 14 | from __future__ import division, unicode_literals, print_function, absolute_import 15 | 16 | from .. import constants 17 | 18 | from .resource import Resource 19 | from .messagebased import MessageBasedResource, ControlRenMixin 20 | 21 | 22 | @Resource.register(constants.InterfaceType.tcpip, 'INSTR') 23 | class TCPIPInstrument(ControlRenMixin, MessageBasedResource): 24 | """Communicates with to devices of type TCPIP::host address[::INSTR] 25 | 26 | More complex resource names can be specified with the following grammar: 27 | TCPIP[board]::host address[::LAN device name][::INSTR] 28 | 29 | Do not instantiate directly, use :meth:`pyvisa.highlevel.ResourceManager.open_resource`. 30 | """ 31 | 32 | 33 | @Resource.register(constants.InterfaceType.tcpip, 'SOCKET') 34 | class TCPIPSocket(MessageBasedResource): 35 | """Communicates with to devices of type TCPIP::host address::port::SOCKET 36 | 37 | More complex resource names can be specified with the following grammar: 38 | TCPIP[board]::host address::port::SOCKET 39 | 40 | Do not instantiate directly, use :meth:`pyvisa.highlevel.ResourceManager.open_resource`. 41 | """ 42 | -------------------------------------------------------------------------------- /pyvisa/resources/usb.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pyvisa.resources.usb 4 | ~~~~~~~~~~~~~~~~~~~~ 5 | 6 | High level wrapper for USB resources. 7 | 8 | This file is part of PyVISA. 9 | 10 | :copyright: 2014 by PyVISA Authors, see AUTHORS for more details. 11 | :license: MIT, see LICENSE for more details. 12 | """ 13 | 14 | from __future__ import division, unicode_literals, print_function, absolute_import 15 | import warnings 16 | 17 | from .. import constants 18 | from .messagebased import MessageBasedResource, ControlRenMixin 19 | 20 | 21 | @MessageBasedResource.register(constants.InterfaceType.usb, 'INSTR') 22 | class USBInstrument(ControlRenMixin, MessageBasedResource): 23 | """Communicates with devices of type USB::manufacturer ID::model code::serial number 24 | 25 | More complex resource names can be specified with the following grammar: 26 | USB[board]::manufacturer ID::model code::serial number[::USB interface number][::INSTR] 27 | 28 | Do not instantiate directly, use :meth:`pyvisa.highlevel.ResourceManager.open_resource`. 29 | """ 30 | 31 | def control_in(self, request_type_bitmap_field, request_id, request_value, index, length=0): 32 | """Performs a USB control pipe transfer from the device. 33 | 34 | :param request_type_bitmap_field: bmRequestType parameter of the setup stage of a USB control transfer. 35 | :param request_id: bRequest parameter of the setup stage of a USB control transfer. 36 | :param request_value: wValue parameter of the setup stage of a USB control transfer. 37 | :param index: wIndex parameter of the setup stage of a USB control transfer. 38 | This is usually the index of the interface or endpoint. 39 | :param length: wLength parameter of the setup stage of a USB control transfer. 40 | This value also specifies the size of the data buffer to receive the data from the 41 | optional data stage of the control transfer. 42 | :return: The data buffer that receives the data from the optional data stage of the control transfer. 43 | :rtype: bytes 44 | """ 45 | return self.visalib.usb_control_in(self.session, request_type_bitmap_field, 46 | request_id, request_value, index, length) 47 | 48 | def control_out(self, request_type_bitmap_field, request_id, request_value, index, data=""): 49 | """Performs a USB control pipe transfer to the device. 50 | 51 | :param request_type_bitmap_field: bmRequestType parameter of the setup stage of a USB control transfer. 52 | :param request_id: bRequest parameter of the setup stage of a USB control transfer. 53 | :param request_value: wValue parameter of the setup stage of a USB control transfer. 54 | :param index: wIndex parameter of the setup stage of a USB control transfer. 55 | This is usually the index of the interface or endpoint. 56 | :param data: The data buffer that sends the data in the optional data stage of the control transfer. 57 | """ 58 | return self.visalib.usb_control_out(self.session, request_type_bitmap_field, 59 | request_id, request_value, index, data) 60 | 61 | def usb_control_out(self, request_type_bitmap_field, request_id, request_value, index, data=""): 62 | """Performs a USB control pipe transfer to the device. (Deprecated) 63 | 64 | :param request_type_bitmap_field: bmRequestType parameter of the setup stage of a USB control transfer. 65 | :param request_id: bRequest parameter of the setup stage of a USB control transfer. 66 | :param request_value: wValue parameter of the setup stage of a USB control transfer. 67 | :param index: wIndex parameter of the setup stage of a USB control transfer. 68 | This is usually the index of the interface or endpoint. 69 | :param data: The data buffer that sends the data in the optional data stage of the control transfer. 70 | """ 71 | warnings.warn('usb_control_out is deprecated use control_out instead.', FutureWarning) 72 | return self.control_out(request_type_bitmap_field, request_id, request_value, index, data) 73 | 74 | 75 | @MessageBasedResource.register(constants.InterfaceType.usb, 'RAW') 76 | class USBRaw(MessageBasedResource): 77 | """Communicates with to devices of type USB::manufacturer ID::model code::serial number::RAW 78 | 79 | More complex resource names can be specified with the following grammar: 80 | USB[board]::manufacturer ID::model code::serial number[::USB interface number]::RAW 81 | 82 | Do not instantiate directly, use :meth:`pyvisa.highlevel.ResourceManager.open_resource`. 83 | """ 84 | -------------------------------------------------------------------------------- /pyvisa/resources/vxi.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pyvisa.resources.vxi 4 | ~~~~~~~~~~~~~~~~~~~~ 5 | 6 | High level wrapper for VXI resources. 7 | 8 | This file is part of PyVISA. 9 | 10 | :copyright: 2014 by PyVISA Authors, see AUTHORS for more details. 11 | :license: MIT, see LICENSE for more details. 12 | """ 13 | 14 | from __future__ import division, unicode_literals, print_function, absolute_import 15 | 16 | from .. import constants 17 | 18 | from .resource import Resource 19 | from .registerbased import RegisterBasedResource 20 | 21 | 22 | @Resource.register(constants.InterfaceType.vxi, 'BACKPLANE') 23 | class VXIBackplane(Resource): 24 | """Communicates with to devices of type VXI::BACKPLANE 25 | 26 | More complex resource names can be specified with the following grammar: 27 | VXI[board][::VXI logical address]::BACKPLANE 28 | 29 | Do not instantiate directly, use :meth:`pyvisa.highlevel.ResourceManager.open_resource`. 30 | """ 31 | 32 | 33 | @Resource.register(constants.InterfaceType.vxi, 'INSTR') 34 | class VXIInstrument(Resource): 35 | """Communicates with to devices of type VXI::VXI logical address[::INSTR] 36 | 37 | More complex resource names can be specified with the following grammar: 38 | VXI[board]::VXI logical address[::INSTR] 39 | 40 | Do not instantiate directly, use :meth:`pyvisa.highlevel.ResourceManager.open_resource`. 41 | """ 42 | 43 | 44 | @Resource.register(constants.InterfaceType.vxi, 'MEMACC') 45 | class VXIMemory(RegisterBasedResource): 46 | """Communicates with to devices of type VXI[board]::MEMACC 47 | 48 | More complex resource names can be specified with the following grammar: 49 | VXI[board]::MEMACC 50 | 51 | Do not instantiate directly, use :meth:`pyvisa.highlevel.ResourceManager.open_resource`. 52 | """ 53 | -------------------------------------------------------------------------------- /pyvisa/testsuite/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from __future__ import (division, unicode_literals, print_function, 4 | absolute_import) 5 | 6 | import os 7 | import logging 8 | import warnings 9 | import unittest 10 | from contextlib import contextmanager 11 | 12 | from logging.handlers import BufferingHandler 13 | 14 | from pyvisa import logger 15 | from pyvisa.compat import PYTHON3 16 | 17 | 18 | class TestHandler(BufferingHandler): 19 | 20 | def __init__(self, only_warnings=False): 21 | # BufferingHandler takes a "capacity" argument 22 | # so as to know when to flush. As we're overriding 23 | # shouldFlush anyway, we can set a capacity of zero. 24 | # You can call flush() manually to clear out the 25 | # buffer. 26 | self.only_warnings = only_warnings 27 | BufferingHandler.__init__(self, 0) 28 | 29 | def shouldFlush(self, record): 30 | return False 31 | 32 | def emit(self, record): 33 | if self.only_warnings and record.level != logging.WARNING: 34 | return 35 | self.buffer.append(record.__dict__) 36 | 37 | 38 | class BaseTestCase(unittest.TestCase): 39 | 40 | CHECK_NO_WARNING = True 41 | 42 | @contextmanager 43 | def capture_log(self, level=logging.DEBUG): 44 | th = TestHandler() 45 | th.setLevel(level) 46 | logger.addHandler(th) 47 | if self._test_handler is None: 48 | yield th.buffer 49 | else: 50 | l = len(self._test_handler.buffer) 51 | yield th.buffer 52 | self._test_handler.buffer = self._test_handler.buffer[:l] 53 | 54 | def setUp(self): 55 | self._test_handler = None 56 | if self.CHECK_NO_WARNING: 57 | self._test_handler = th = TestHandler() 58 | th.setLevel(logging.WARNING) 59 | logger.addHandler(th) 60 | 61 | def tearDown(self): 62 | if self._test_handler is not None: 63 | buf = self._test_handler.buffer 64 | l = len(buf) 65 | msg = '\n'.join(record.get('msg', str(record)) for record in buf) 66 | self.assertEqual(l, 0, msg='%d warnings raised.\n%s' % (l, msg)) 67 | 68 | if not PYTHON3: 69 | @contextmanager 70 | def assertWarns(self, category): 71 | """Backport for Python 2 72 | 73 | """ 74 | with warnings.catch_warnings(record=True) as w: 75 | # Cause all warnings to always be triggered. 76 | warnings.simplefilter("always") 77 | # Trigger a warning. 78 | yield 79 | # Verify some things 80 | assert len(w) == 1, 'No warning raised' 81 | assert issubclass(w[-1].category, category) 82 | 83 | 84 | def testsuite(): 85 | """A testsuite that has all the pyvisa tests. 86 | """ 87 | return unittest.TestLoader().discover(os.path.dirname(__file__)) 88 | 89 | 90 | def main(): 91 | """Runs the testsuite as command line application. 92 | """ 93 | try: 94 | unittest.main() 95 | except Exception as e: 96 | print('Error: %s' % e) 97 | 98 | 99 | def run(): 100 | """Run all tests. 101 | 102 | :return: a :class:`unittest.TestResult` object 103 | """ 104 | test_runner = unittest.TextTestRunner() 105 | return test_runner.run(testsuite()) 106 | -------------------------------------------------------------------------------- /pyvisa/testsuite/test_errors.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from __future__ import division, unicode_literals, print_function, absolute_import 4 | 5 | import pickle 6 | 7 | from pyvisa.testsuite import BaseTestCase 8 | 9 | from pyvisa import errors 10 | 11 | 12 | class TestPicleUnpickle(BaseTestCase): 13 | def _test_pickle_unpickle(self, instance): 14 | pickled = pickle.dumps(instance) 15 | unpickled = pickle.loads(pickled) 16 | self.assertIsInstance(unpickled, type(instance)) 17 | for attr in instance.__dict__: 18 | self.assertEqual(getattr(instance, attr), 19 | getattr(unpickled, attr)) 20 | 21 | def test_VisaIOError(self): 22 | self._test_pickle_unpickle(errors.VisaIOError(0)) 23 | 24 | def test_VisaIOWarning(self): 25 | self._test_pickle_unpickle(errors.VisaIOWarning(0)) 26 | 27 | def test_UnknownHandler(self): 28 | self._test_pickle_unpickle(errors.UnknownHandler(0,0,0)) 29 | 30 | def test_OSNotSupported(self): 31 | self._test_pickle_unpickle(errors.OSNotSupported("")) 32 | 33 | def test_InvalidBinaryFormat(self): 34 | self._test_pickle_unpickle(errors.InvalidBinaryFormat()) 35 | 36 | def InvalidSession(self): 37 | self._test_pickle_unpickle(errors.InvalidSession()) 38 | -------------------------------------------------------------------------------- /pyvisa/testsuite/test_rname.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from __future__ import (division, unicode_literals, print_function, 4 | absolute_import) 5 | 6 | import unittest 7 | from pyvisa.testsuite import BaseTestCase 8 | 9 | from pyvisa import rname 10 | 11 | parse = rname.ResourceName.from_string 12 | 13 | 14 | class TestParsers(BaseTestCase): 15 | 16 | def _parse_test(self, rn, **kwargs): 17 | p = parse(rn) 18 | r = dict((k, getattr(p, k)) for k in p._fields + ('interface_type', 'resource_class')) 19 | r['canonical_resource_name'] = str(p) 20 | self.assertEqual(r, kwargs, rn) 21 | 22 | @unittest.expectedFailure 23 | def test_asrl_ethernet(self): 24 | self._parse_test('ASRL::1.2.3.4::2::INSTR', 25 | interface_type='ASRL', 26 | resource_class='INSTR', 27 | port='2', 28 | address='1.2.3.4') 29 | 30 | def test_asrl(self): 31 | self._parse_test('ASRL1::INSTR', 32 | interface_type='ASRL', 33 | resource_class='INSTR', 34 | board='1', 35 | canonical_resource_name='ASRL1::INSTR') 36 | 37 | self._parse_test('ASRL1', 38 | interface_type='ASRL', 39 | resource_class='INSTR', 40 | board='1', 41 | canonical_resource_name='ASRL1::INSTR') 42 | 43 | def test_gpib_instr(self): 44 | self._parse_test('GPIB::1::1::INSTR', 45 | interface_type='GPIB', 46 | resource_class='INSTR', 47 | board='0', 48 | primary_address='1', 49 | secondary_address='1', 50 | canonical_resource_name='GPIB0::1::1::INSTR') 51 | 52 | self._parse_test('GPIB::1::INSTR', 53 | interface_type='GPIB', 54 | resource_class='INSTR', 55 | board='0', 56 | primary_address='1', 57 | secondary_address='0', 58 | canonical_resource_name='GPIB0::1::0::INSTR') 59 | 60 | self._parse_test('GPIB1::1::INSTR', 61 | interface_type='GPIB', 62 | resource_class='INSTR', 63 | board='1', 64 | primary_address='1', 65 | secondary_address='0', 66 | canonical_resource_name='GPIB1::1::0::INSTR') 67 | 68 | self._parse_test('GPIB1::1', 69 | interface_type='GPIB', 70 | resource_class='INSTR', 71 | board='1', 72 | primary_address='1', 73 | secondary_address='0', 74 | canonical_resource_name='GPIB1::1::0::INSTR') 75 | 76 | def test_gpib_intf(self): 77 | self._parse_test('GPIB::INTFC', 78 | interface_type='GPIB', 79 | resource_class='INTFC', 80 | board='0', 81 | canonical_resource_name='GPIB0::INTFC') 82 | 83 | self._parse_test('GPIB3::INTFC', 84 | interface_type='GPIB', 85 | resource_class='INTFC', 86 | board='3', 87 | canonical_resource_name='GPIB3::INTFC') 88 | 89 | def test_tcpip_intr(self): 90 | 91 | self._parse_test('TCPIP::192.168.134.102', 92 | interface_type='TCPIP', 93 | resource_class='INSTR', 94 | host_address='192.168.134.102', 95 | board='0', 96 | lan_device_name='inst0', 97 | canonical_resource_name='TCPIP0::192.168.134.102::inst0::INSTR') 98 | 99 | self._parse_test('TCPIP::dev.company.com::INSTR', 100 | interface_type='TCPIP', 101 | resource_class='INSTR', 102 | host_address='dev.company.com', 103 | board='0', 104 | lan_device_name='inst0', 105 | canonical_resource_name='TCPIP0::dev.company.com::inst0::INSTR') 106 | 107 | self._parse_test('TCPIP3::dev.company.com::inst3::INSTR', 108 | interface_type='TCPIP', 109 | resource_class='INSTR', 110 | host_address='dev.company.com', 111 | board='3', 112 | lan_device_name='inst3', 113 | canonical_resource_name='TCPIP3::dev.company.com::inst3::INSTR') 114 | 115 | self._parse_test('TCPIP3::1.2.3.4::inst3::INSTR', 116 | interface_type='TCPIP', 117 | resource_class='INSTR', 118 | host_address='1.2.3.4', 119 | board='3', 120 | lan_device_name='inst3', 121 | canonical_resource_name='TCPIP3::1.2.3.4::inst3::INSTR') 122 | 123 | def test_tcpip_socket(self): 124 | self._parse_test('TCPIP::1.2.3.4::999::SOCKET', 125 | interface_type='TCPIP', 126 | resource_class='SOCKET', 127 | host_address='1.2.3.4', 128 | board='0', 129 | port='999', 130 | canonical_resource_name='TCPIP0::1.2.3.4::999::SOCKET') 131 | 132 | self._parse_test('TCPIP2::1.2.3.4::999::SOCKET', 133 | interface_type='TCPIP', 134 | resource_class='SOCKET', 135 | host_address='1.2.3.4', 136 | board='2', 137 | port='999', 138 | canonical_resource_name='TCPIP2::1.2.3.4::999::SOCKET') 139 | 140 | def test_usb_instr(self): 141 | self._parse_test('USB::0x1234::125::A22-5::INSTR', 142 | interface_type='USB', 143 | resource_class='INSTR', 144 | manufacturer_id='0x1234', 145 | model_code='125', 146 | serial_number='A22-5', 147 | board='0', 148 | usb_interface_number='0', 149 | canonical_resource_name='USB0::0x1234::125::A22-5::0::INSTR') 150 | 151 | self._parse_test('USB2::0x1234::125::A22-5::INSTR', 152 | interface_type='USB', 153 | resource_class='INSTR', 154 | manufacturer_id='0x1234', 155 | model_code='125', 156 | serial_number='A22-5', 157 | board='2', 158 | usb_interface_number='0', 159 | canonical_resource_name='USB2::0x1234::125::A22-5::0::INSTR') 160 | 161 | self._parse_test('USB::0x1234::125::A22-5', 162 | interface_type='USB', 163 | resource_class='INSTR', 164 | manufacturer_id='0x1234', 165 | model_code='125', 166 | serial_number='A22-5', 167 | board='0', 168 | usb_interface_number='0', 169 | canonical_resource_name='USB0::0x1234::125::A22-5::0::INSTR') 170 | 171 | self._parse_test('USB::0x1234::125::A22-5::3::INSTR', 172 | interface_type='USB', 173 | resource_class='INSTR', 174 | manufacturer_id='0x1234', 175 | model_code='125', 176 | serial_number='A22-5', 177 | board='0', 178 | usb_interface_number='3', 179 | canonical_resource_name='USB0::0x1234::125::A22-5::3::INSTR') 180 | 181 | self._parse_test('USB2::0x1234::125::A22-5::3::INSTR', 182 | interface_type='USB', 183 | resource_class='INSTR', 184 | manufacturer_id='0x1234', 185 | model_code='125', 186 | serial_number='A22-5', 187 | board='2', 188 | usb_interface_number='3', 189 | canonical_resource_name='USB2::0x1234::125::A22-5::3::INSTR') 190 | 191 | self._parse_test('USB1::0x1234::125::A22-5::3', 192 | interface_type='USB', 193 | resource_class='INSTR', 194 | manufacturer_id='0x1234', 195 | model_code='125', 196 | serial_number='A22-5', 197 | board='1', 198 | usb_interface_number='3', 199 | canonical_resource_name='USB1::0x1234::125::A22-5::3::INSTR') 200 | 201 | def test_usb_raw(self): 202 | self._parse_test('USB::0x1234::125::A22-5::RAW', 203 | interface_type='USB', 204 | resource_class='RAW', 205 | manufacturer_id='0x1234', 206 | model_code='125', 207 | serial_number='A22-5', 208 | board='0', 209 | usb_interface_number='0', 210 | canonical_resource_name='USB0::0x1234::125::A22-5::0::RAW') 211 | 212 | self._parse_test('USB2::0x1234::125::A22-5::RAW', 213 | interface_type='USB', 214 | resource_class='RAW', 215 | manufacturer_id='0x1234', 216 | model_code='125', 217 | serial_number='A22-5', 218 | board='2', 219 | usb_interface_number='0', 220 | canonical_resource_name='USB2::0x1234::125::A22-5::0::RAW') 221 | 222 | self._parse_test('USB2::0x1234::125::A22-5::3::RAW', 223 | interface_type='USB', 224 | resource_class='RAW', 225 | manufacturer_id='0x1234', 226 | model_code='125', 227 | serial_number='A22-5', 228 | board='2', 229 | usb_interface_number='3', 230 | canonical_resource_name='USB2::0x1234::125::A22-5::3::RAW') 231 | 232 | class TestFilters(BaseTestCase): 233 | 234 | run_list = ( 235 | 'GPIB0::8::65535::INSTR', 236 | 'TCPIP0::localhost:1111::inst0::INSTR', 237 | 'ASRL1::INSTR', 238 | 'USB0::0x1111::0x2222::0x4445::0::RAW', 239 | 'USB0::0x1111::0x2222::0x1234::0::INSTR', 240 | 'TCPIP0::localhost::10001::SOCKET', 241 | 'GPIB9::8::65535::INSTR', 242 | 'ASRL11::INSTR', 243 | 'ASRL2::INSTR' 244 | ) 245 | 246 | def _test_filter(self, expr, *correct): 247 | ok = tuple(self.run_list[n] for n in correct) 248 | self.assertEqual(rname.filter(self.run_list, expr), ok) 249 | 250 | def test_filter(self): 251 | self._test_filter('?*::INSTR', 0, 1, 2, 4, 6, 7, 8) 252 | self._test_filter('GPIB?+INSTR', 0, 6) 253 | self._test_filter('GPIB[0-8]*::?*INSTR', 0) 254 | self._test_filter('GPIB[^0]::?*INSTR', 6) 255 | self._test_filter('ASRL1+::INSTR', 2, 7) 256 | self._test_filter('(GPIB|VXI)?*INSTR', 0, 6) 257 | self._test_filter('?*', *tuple(range(len(self.run_list)))) 258 | -------------------------------------------------------------------------------- /pyvisa/testsuite/test_util.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from __future__ import (division, unicode_literals, print_function, 4 | absolute_import) 5 | 6 | from pyvisa.testsuite import BaseTestCase 7 | 8 | from pyvisa import util 9 | 10 | try: 11 | # noinspection PyPackageRequirements 12 | import numpy as np 13 | except ImportError: 14 | np = None 15 | 16 | 17 | class TestParser(BaseTestCase): 18 | 19 | def test_parse_binary(self): 20 | s = (b'#A@\xe2\x8b<@\xe2\x8b<@\xe2\x8b<@\xe2\x8b<@\xde\x8b<@\xde\x8b<@' 21 | b'\xde\x8b<@\xde\x8b<@\xe0\x8b<@\xe0\x8b<@\xdc\x8b<@\xde\x8b<@' 22 | b'\xe2\x8b<@\xe0\x8b<') 23 | e = [0.01707566, 0.01707566, 0.01707566, 0.01707566, 0.01707375, 24 | 0.01707375, 0.01707375, 0.01707375, 0.01707470, 0.01707470, 25 | 0.01707280, 0.01707375, 0.01707566, 0.01707470] 26 | with self.assertWarns(FutureWarning): 27 | p = util.parse_binary(s, is_big_endian=False, is_single=True) 28 | for a, b in zip(p, e): 29 | self.assertAlmostEqual(a, b) 30 | 31 | # Test handling indefinite length block 32 | p = util.from_ieee_block(s, datatype='f', is_big_endian=False) 33 | for a, b in zip(p, e): 34 | self.assertAlmostEqual(a, b) 35 | 36 | # Test handling definite length block 37 | p = util.from_ieee_block(b'#214' + s[2:], datatype='f', 38 | is_big_endian=False) 39 | for a, b in zip(p, e): 40 | self.assertAlmostEqual(a, b) 41 | 42 | p = util.from_hp_block(b'#A\x0e\x00' + s[2:], datatype='f', 43 | is_big_endian=False) 44 | for a, b in zip(p, e): 45 | self.assertAlmostEqual(a, b) 46 | 47 | def test_integer_ascii_block(self): 48 | values = list(range(99)) 49 | for fmt in 'd': 50 | msg = 'block=%s, fmt=%s' 51 | msg = msg % ('ascii', fmt) 52 | tb = lambda values: util.to_ascii_block(values, fmt, ',') 53 | fb = lambda block, cont: util.from_ascii_block(block, fmt, ',', 54 | cont) 55 | self.round_trip_block_converstion(values, tb, fb, msg) 56 | 57 | def test_non_integer_ascii_block(self): 58 | values = [val + 0.5 for val in range(99)] 59 | values = list(range(99)) 60 | for fmt in 'fFeEgG': 61 | msg = 'block=%s, fmt=%s' 62 | msg = msg % ('ascii', fmt) 63 | tb = lambda values: util.to_ascii_block(values, fmt, ',') 64 | fb = lambda block, cont: util.from_ascii_block(block, fmt, ',', 65 | cont) 66 | self.round_trip_block_converstion(values, tb, fb, msg) 67 | 68 | def test_integer_binary_block(self): 69 | values = list(range(99)) 70 | for block, tb, fb in zip(('ieee', 'hp'), 71 | (util.to_ieee_block, util.to_hp_block), 72 | (util.from_ieee_block, util.from_hp_block)): 73 | for fmt in 'bBhHiIfd': 74 | for endi in (True, False): 75 | msg = 'block=%s, fmt=%s, endianness=%s' 76 | msg = msg % (block, fmt, endi) 77 | tblock = lambda values: tb(values, fmt, endi) 78 | fblock = lambda block, cont: fb(block, fmt, endi, cont) 79 | self.round_trip_block_converstion(values, tblock, fblock, 80 | msg) 81 | 82 | def test_noninteger_binary_block(self): 83 | values = [val + 0.5 for val in range(99)] 84 | for block, tb, fb in zip(('ieee', 'hp'), 85 | (util.to_ieee_block, util.to_hp_block), 86 | (util.from_ieee_block, util.from_hp_block)): 87 | for fmt in 'fd': 88 | for endi in (True, False): 89 | msg = 'block=%s, fmt=%s, endianness=%s' 90 | msg = msg % (block, fmt, endi) 91 | tblock = lambda values: bytearray(tb(values, fmt, endi)) 92 | fblock = lambda block, cont: fb(block, fmt, endi, cont) 93 | self.round_trip_block_converstion(values, tblock, fblock, 94 | msg) 95 | 96 | def round_trip_block_converstion(self, values, to_block, from_block, msg): 97 | """Test that block conversion round trip as expected. 98 | 99 | """ 100 | containers = (list, tuple) + ((np.array,) if np else ()) 101 | for cont in containers: 102 | conv = cont(values) 103 | msg += ', container=%s' 104 | msg = msg % cont.__name__ 105 | try: 106 | block = to_block(conv) 107 | parsed = from_block(block, cont) 108 | except Exception as e: 109 | raise Exception(msg + '\n' + repr(e)) 110 | 111 | if np and cont in (np.array,): 112 | np.testing.assert_array_equal(conv, parsed, msg) 113 | else: 114 | self.assertEqual(conv, parsed, msg) 115 | -------------------------------------------------------------------------------- /pyvisa/thirdparty/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pyvisa.thirdparty 4 | ~~~~~~~~~~~~~~~~~ 5 | 6 | Third party libraries and modules bundled with PyVISA. 7 | 8 | This file is part of PyVISA. 9 | 10 | :copyright: 2014 by PyVISA Authors, see AUTHORS for more details. 11 | :license: MIT, see LICENSE for more details. 12 | """ 13 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [check-manifest] 2 | ignore = 3 | .travis.yml 4 | tox.ini 5 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import sys 5 | 6 | try: 7 | from setuptools import setup 8 | except ImportError: 9 | print('Please install or upgrade setuptools or pip to continue') 10 | sys.exit(1) 11 | 12 | 13 | def read(filename): 14 | with open(filename, 'rb') as f: 15 | return f.read().decode('utf8') 16 | 17 | 18 | long_description = '\n\n'.join([read('README'), 19 | read('AUTHORS'), 20 | read('CHANGES')]) 21 | 22 | __doc__ = long_description 23 | 24 | requirements = [] 25 | if sys.version_info < (3,): 26 | requirements.append('enum34') 27 | 28 | setup(name='PyVISA', 29 | description='Python VISA bindings for GPIB, RS232, TCPIP and USB instruments', 30 | version='1.10.0.dev', 31 | long_description=long_description, 32 | author='Torsten Bronger, Gregor Thalhammer', 33 | author_email='bronger@physik.rwth-aachen.de', 34 | maintainer='Hernan E. Grecco', 35 | maintainer_email='hernan.grecco@gmail.com', 36 | url='https://github.com/pyvisa/pyvisa', 37 | test_suite='pyvisa.testsuite.testsuite', 38 | keywords='VISA GPIB USB serial RS232 measurement acquisition', 39 | license='MIT License', 40 | python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*', 41 | install_requires=requirements, 42 | classifiers=[ 43 | 'Development Status :: 5 - Production/Stable', 44 | 'Intended Audience :: Developers', 45 | 'Intended Audience :: Science/Research', 46 | 'License :: OSI Approved :: MIT License', 47 | 'Operating System :: Microsoft :: Windows', 48 | 'Operating System :: POSIX :: Linux', 49 | 'Operating System :: MacOS :: MacOS X', 50 | 'Programming Language :: Python', 51 | 'Topic :: Scientific/Engineering :: Interface Engine/Protocol Translator', 52 | 'Topic :: Software Development :: Libraries :: Python Modules', 53 | 'Programming Language :: Python :: 2', 54 | 'Programming Language :: Python :: 2.7', 55 | 'Programming Language :: Python :: 3', 56 | 'Programming Language :: Python :: 3.4', 57 | 'Programming Language :: Python :: 3.5', 58 | 'Programming Language :: Python :: 3.6', 59 | ], 60 | packages=['pyvisa', 'pyvisa.compat', 61 | 'pyvisa.ctwrapper', 62 | 'pyvisa.resources', 63 | 'pyvisa.thirdparty', 64 | 'pyvisa.testsuite'], 65 | platforms="Linux, Windows,Mac", 66 | entry_points={'console_scripts': 67 | ['pyvisa-shell=visa:visa_shell', 68 | 'pyvisa-info=visa:visa_info']}, 69 | py_modules=['visa'], 70 | use_2to3=False, 71 | zip_safe=False) 72 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py27,py34,py35,py36 3 | 4 | [testenv] 5 | deps= 6 | pytest 7 | sphinx 8 | mock 9 | 10 | commands= 11 | py.test 12 | -------------------------------------------------------------------------------- /visa.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | pyvisa.visa 4 | ~~~~~~~~~~~ 5 | 6 | Module to provide an import shortcut for the most common VISA operations. 7 | 8 | This file is part of PyVISA. 9 | 10 | :copyright: 2014 by PyVISA Authors, see AUTHORS for more details. 11 | :license: MIT, see COPYING for more details. 12 | """ 13 | 14 | from __future__ import division, unicode_literals, print_function, absolute_import 15 | 16 | from pyvisa import logger, __version__, log_to_screen, constants 17 | from pyvisa.highlevel import ResourceManager 18 | from pyvisa.errors import (Error, VisaIOError, VisaIOWarning, VisaTypeError, 19 | UnknownHandler, OSNotSupported, InvalidBinaryFormat, 20 | InvalidSession, LibraryError) 21 | # This is needed to registry all resources. 22 | from pyvisa.resources import Resource 23 | 24 | def visa_main(command=None): 25 | import argparse 26 | parser = argparse.ArgumentParser(description='PyVISA command-line utilities') 27 | 28 | parser.add_argument('--backend', '-b', dest='backend', action='store', default=None, 29 | help='backend to be used (default: ni)') 30 | 31 | if not command: 32 | subparsers = parser.add_subparsers(title='command', dest='command') 33 | 34 | info_parser = subparsers.add_parser('info', help='print information to diagnose PyVISA') 35 | 36 | console_parser = subparsers.add_parser('shell', help='start the PyVISA console') 37 | 38 | args = parser.parse_args() 39 | if command: 40 | args.command = command 41 | if args.command == 'info': 42 | from pyvisa import util 43 | util.get_debug_info() 44 | elif args.command == 'shell': 45 | from pyvisa import shell 46 | shell.main('@' + args.backend if args.backend else '') 47 | 48 | def visa_shell(): 49 | visa_main('shell') 50 | 51 | def visa_info(): 52 | visa_main('info') 53 | 54 | if __name__ == '__main__': 55 | visa_main() 56 | --------------------------------------------------------------------------------