Esempio n. 1
0
def test_raises():
    with pytest.raises(OSError, match=r'^Cannot find'):
        with LoadLibrary('doesnotexist'):
            pass

    path = os.path.join(EXAMPLES_DIR, 'Trig.class')
    with pytest.raises(ValueError, match=r'^Cannot load libtype'):
        with LoadLibrary(path, libtype='invalid'):
            pass
Esempio n. 2
0
def enumerate_units():
    """Find the PicoScopes that are connected to the computer.
    
    This function counts the number of PicoScopes connected to the
    computer, and returns a list of serial numbers as a string.

    Note
    ----
    You cannot call this function after you have opened a connection to a PicoScope.
    
    Returns
    -------
    :class:`list` of :class:`str`
        A list of serial numbers of the PicoScopes that were found.
    """
    count = c_int16()
    size = c_int16(1023)
    serials = (c_int8 * size.value)()
    libtype = 'windll' if IS_WINDOWS else 'cdll'
    sdk = LoadLibrary('ps5000a', libtype)
    result = sdk.lib.ps5000aEnumerateUnits(byref(count), byref(serials),
                                           byref(size))
    if result != PICO_OK:
        if result == PICO_NOT_FOUND:
            err_name, err_msg = 'PICO_NOT_FOUND', 'Are you sure that a PicoScope is connected to the computer?'
        else:
            err_name, err_msg = ERROR_CODES_API.get(
                result, ('UnhandledError', 'Error code 0x{:x}'.format(result)))
        raise PicoTechError('Cannot enumerate units.\n{}: {}'.format(
            err_name, err_msg))
    return string_at(addressof(serials)).decode('utf-8').split(',')
Esempio n. 3
0
def test_java(caplog):
    caplog.set_level(logging.DEBUG, logger.name)
    path = os.path.join(EXAMPLES_DIR, 'Trig.class')
    with LoadLibrary(path) as library:
        assert library.assembly is None
        assert isinstance(library.gateway, JavaGateway)
        assert library.path == path
        assert isinstance(library.lib, JVMView)
        assert library.lib.Trig.cos(0.0) == 1.0
    assert library.path == path
    assert library.assembly is None
    assert library.gateway is None
    assert library.lib is None

    record = caplog.records[0]
    assert record.levelname == 'DEBUG'
    assert record.msg == 'Loaded ' + library.path

    record = caplog.records[1]
    assert record.levelname == 'DEBUG'
    assert record.msg == 'shutdown Py4J.GatewayServer'

    # can still call this (even multiple times)
    for _ in range(10):
        library.cleanup()

    assert 'libtype=NoneType' in str(library)
    assert 'libtype=NoneType' in repr(library)
Esempio n. 4
0
 def error2(self):
     try:
         LoadLibrary('ABC.DEF.GHI', 'activex')
     except OSError as e:
         return str(e)
     else:
         raise OSError('Did not raise OSError')
Esempio n. 5
0
    def run():
        assert comtypes.client.gen_dir.endswith('site-packages\\comtypes\\gen')

        # do not want to save any files in the site-packages/comtypes/gen directory
        # when the LoadLibrary class is called
        if not os.path.isdir(out_dir):
            os.makedirs(out_dir)
        cached_gen_dir = comtypes.client.gen_dir
        comtypes.client.gen_dir = out_dir
        com = LoadLibrary('InternetExplorer.Application.1', 'com')
        comtypes.client.gen_dir = cached_gen_dir
        cleanup()

        assert comtypes.client.gen_dir.endswith('site-packages\\comtypes\\gen')

        items = [
            'InternetExplorer.Application.1',  # ProgID
            '{0002DF01-0000-0000-C000-000000000046}',  # CLSID
            'shdocvw.dll',  # type library file
            ['{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}', 1, 1],  # [guid, major, minor]
            com,  # LoadLibrary object
            com.lib,  # a COM pointer instance
        ]
        for item in items:
            # make sure that each iteration through this loop generates a new
            # 'mod' object and comtypes does not load the object from the
            # previous loop iteration
            assert not os.path.isdir(out_dir)
            for name in expected_mod_names:
                assert name not in sys.modules

            mod = utils.generate_com_wrapper(item, out_dir=out_dir)
            assert mod.__name__ == expected_mod_names[0]
            assert mod.IWebBrowser2
            for name in expected_mod_names:
                filename = name.split('.')[2] + '.py'
                assert os.path.isfile(os.path.join(out_dir, filename))

            cleanup()

        assert comtypes.client.gen_dir.endswith('site-packages\\comtypes\\gen')

        with pytest.raises(OSError):
            utils.generate_com_wrapper('progid.does.not.exist')

        assert comtypes.client.gen_dir.endswith('site-packages\\comtypes\\gen')

        # a non-LoadLib object should still raise AttributeError
        for obj in [dict(), None, True]:
            with pytest.raises(AttributeError):
                utils.generate_com_wrapper(obj)

        assert comtypes.client.gen_dir.endswith('site-packages\\comtypes\\gen')
def device_manager():
    """Returns a reference to the DeviceManager library.
    
    The ``Thorlabs.MotionControl.DeviceManager.dll`` library must be available on
    :data:`os.environ['PATH'] <os.environ>`.

    Returns
    -------
    :class:`ctypes.CDLL`
        A reference to the library.
    """
    global _motion_control_device_manager
    if _motion_control_device_manager is None:
        _motion_control_device_manager = LoadLibrary('Thorlabs.MotionControl.DeviceManager.dll').lib
    return _motion_control_device_manager
Esempio n. 7
0
    def __init__(self, path, libtype, host, port, quiet):
        """Base class for loading a 32-bit library in 32-bit Python.

        All modules that are to be run on the 32-bit server must contain a class
        that is inherited from this class and the module can import **any** of
        the `standard`_ python modules **except** for :mod:`distutils`,
        :mod:`ensurepip`, :mod:`tkinter` and :mod:`turtle`.

        All modules that are run on the 32-bit server must be able to run on the Python
        interpreter that the server is running on, see :meth:`.version` for how to
        determine the version of the Python interpreter.

        .. _standard: https://docs.python.org/3/py-modindex.html
        .. _JVM: https://en.wikipedia.org/wiki/Java_virtual_machine

        Parameters
        ----------
        path : :class:`str`
            The path to the 32-bit library.
        libtype : :class:`str`
            The library type to use for the calling convention. One of the following:

                * ``'cdll'`` -- for a __cdecl library
                * ``'windll'`` or ``'oledll'`` -- for a __stdcall library (Windows only)
                * ``'net'`` -- for a .NET library

            .. note::
               Since Java byte code is executed on the JVM_ it does not make sense to
               use :class:`Serve32` for a Java ``.jar`` or ``.class`` file.

        host : :class:`str`
            The IP address of the server.
        port : :class:`int`
            The port to open on the server.
        quiet : :class:`bool`
            Whether to hide :obj:`sys.stdout` messages from the server.

        Raises
        ------
        IOError
            If the shared library cannot be loaded.
        TypeError
            If the value of `libtype` is not supported.
        """
        HTTPServer.__init__(self, (host, int(port)), RequestHandler)
        self.quiet = quiet
        self._library = LoadLibrary(path, libtype)
Esempio n. 8
0
    def __init__(self, record, libtype, path=None):
        """Base class for equipment that use the SDK provided by the manufacturer
        for the connection.

        The :data:`~msl.equipment.record_types.ConnectionRecord.backend`
        value must be equal to :data:`~msl.equipment.constants.Backend.MSL`
        to use this class for the communication system. This is achieved by
        setting the value in the **Backend** field for a connection record
        in the :ref:`connections-database` to be ``MSL``.

        Do not instantiate this class directly. Use the
        :meth:`~.EquipmentRecord.connect` method to connect to the equipment.

        Parameters
        ----------
        record : :class:`.EquipmentRecord`
            A record from an :ref:`equipment-database`.
        libtype : :class:`str`
            The library type. See :class:`~msl.loadlib.load_library.LoadLibrary`
            for more information.
        path : :class:`str`, optional
            The path to the SDK (if `record.connection.address` does not contain
            this information).

        Raises
        ------
        IOError
            If the shared library cannot be loaded.
        TypeError
            If either `record` or `libtype` is invalid.
        """
        super(ConnectionSDK, self).__init__(record)

        if path is None:
            info = ConnectionSDK.parse_address(record.connection.address)
            if info is None:
                self.raise_exception('Invalid address for {!r}'.format(
                    self.__class__.__name__))
            path = info['path']

        self._lib = LoadLibrary(path, libtype)
        self._path = self._lib.path
        self._sdk = self._lib.lib
        self._assembly = self._lib.assembly
        self._gateway = self._lib.gateway

        self.log_debug('Connected to {}'.format(record.connection))
Esempio n. 9
0
def enumerate_units(comm_type='all'):
    """Find PT-104 Platinum Resistance Data Logger's.

    This routine returns a list of all the attached PT-104 devices of the specified
    communication type.

    Note
    ----
    You cannot call this function after you have opened a connection to a Data Logger.

    Parameters
    ----------
    comm_type : :class:`str`, optional
        The communication type used by the PT-104. Can be any of the following values:
        ``'usb'``, ``'ethernet'``, ``'enet'``, ``'all'``

    Returns
    -------
    :class:`list` of :class:`str`
        A list of serial numbers of the PT-104 Data Loggers that were found.
    """
    length = c_uint32(1023)
    details = (c_int8 * length.value)()

    t = comm_type.lower()
    if t == 'usb':
        t_val = 0x00000001
    elif t == 'ethernet' or t == 'enet':
        t_val = 0x00000002
    elif t == 'all':
        t_val = 0xFFFFFFFF
    else:
        raise PicoTechError('Invalid communication type {}'.format(comm_type))

    libtype = 'windll' if IS_WINDOWS else 'cdll'
    sdk = LoadLibrary('usbpt104', libtype)
    result = sdk.lib.UsbPt104Enumerate(byref(details), byref(length), t_val)
    if result != PICO_OK:
        if result == PICO_NOT_FOUND:
            err_name, err_msg = 'PICO_NOT_FOUND', 'Are you sure that a PT-104 is connected to the computer?'
        else:
            err_name, err_msg = ERROR_CODES_API.get(
                result, ('UnhandledError', 'Error code 0x{:x}'.format(result)))
        raise PicoTechError('Cannot enumerate units.\n{}: {}'.format(
            err_name, err_msg))
    return string_at(addressof(details)).decode('utf-8').split(',')
Esempio n. 10
0
def test_cpp():
    path = os.path.join(EXAMPLES_DIR, 'cpp_lib' + suffix + DEFAULT_EXTENSION)
    with LoadLibrary(path) as library:
        assert library.assembly is None
        assert library.gateway is None
        assert library.path == path
        assert isinstance(library.lib, CDLL)
        assert library.lib.add(1, 2) == 3
    assert library.path == path
    assert library.assembly is None
    assert library.gateway is None
    assert library.lib is None

    # can still call this (even multiple times)
    for _ in range(10):
        library.cleanup()

    assert 'libtype=NoneType' in str(library)
    assert 'libtype=NoneType' in repr(library)
Esempio n. 11
0
def test_dotnet():
    path = os.path.join(EXAMPLES_DIR, 'dotnet_lib' + suffix + '.dll')
    with LoadLibrary(path, libtype='net') as library:
        assert isinstance(library.assembly, library.lib.System.Reflection.Assembly)
        assert library.assembly is not None
        assert library.gateway is None
        assert library.path == path
        assert isinstance(library.lib, DotNet)
        assert library.lib.DotNetMSL.BasicMath().add_integers(1, 2) == 3
    assert library.path == path
    assert library.assembly is None
    assert library.gateway is None
    assert library.lib is None

    # can still call this (even multiple times)
    for _ in range(10):
        library.cleanup()

    assert 'libtype=NoneType' in str(library)
    assert 'libtype=NoneType' in repr(library)
Esempio n. 12
0
def test_framework_v2():
    # The python.exe.config file must exist before the Python interpreter
    # starts in order for pythonnet to load a library from .NET <4.0. That
    # is why we must use subprocess for this test. The 'legacy_v2_runtime.py'
    # script must be run in a different Python process which depends on
    # whether python.exe.config exists before the subprocess runs.
    #
    # This test also requires that the .NET Framework 3.5 is installed.
    # If it is not, this test will fail with a missing-dependency error:
    #
    #   System.IO.FileLoadException: Could not load file or assembly
    #   'legacy_v2_runtime_x64.dll' or one of its dependencies.
    #

    root_dir = os.path.join(os.path.dirname(__file__), 'dotnet_config')
    script = os.path.join(root_dir, 'legacy_v2_runtime.py')

    assert os.path.isfile(script)

    if os.path.isfile(config_path):
        os.remove(config_path)

    # the python.exe.config file gets created
    assert not os.path.isfile(config_path)
    p = Popen([sys.executable, script], stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate()
    assert not stdout
    assert b'useLegacyV2RuntimeActivationPolicy property was added' in stderr

    # the script now runs without error
    p = Popen([sys.executable, script], stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate()
    assert not stderr
    assert stdout.rstrip() == b'SUCCESS'

    # the above tests also depend on LoadLibrary raising OSError
    # if the DLL file does not exist
    with pytest.raises(OSError, match=r"Cannot find '.*legacy_v2_runtime.dll' for libtype='clr'"):
        LoadLibrary(os.path.join(root_dir, 'legacy_v2_runtime.dll'), libtype='clr')
Esempio n. 13
0
import random

import clr

# make sure 'msl.loadlib' is available on PATH before importing it
path = os.path.abspath(
    os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
sys.path.insert(0, path)

from msl.loadlib import (
    IS_PYTHON_64BIT,
    LoadLibrary,
)

bitness = 'x64' if IS_PYTHON_64BIT else 'x86'
filename = 'legacy_v2_runtime_{}.dll'.format(bitness)
path = os.path.join(os.path.dirname(__file__), 'legacy_v2_runtime', filename)

# this is not necessary, just wanted to randomly select
# one of the supported .NET libtype's
libtype = 'clr' if random.random() > 0.5 else 'net'

net = LoadLibrary(path, libtype=libtype)

expected = 'Microsoft Visual Studio 2005 (Version 8.0.50727.42); Microsoft .NET Framework (Version 2.0.50727)'
environment = net.lib.legacy.Build().Environment()
if environment != expected:
    sys.exit('{!r} != {!r}'.format(environment, expected))

print('SUCCESS')
Esempio n. 14
0
#!/usr/bin/python3

from csbiginteger.BigInteger import BigInteger

from functools import total_ordering

# requires: pip install msl-loadlib pycparser pythonnet
from msl.loadlib import LoadLibrary

# remember to execute first: cd csbiginteger/dotnet && dotnet build -c Release
net = LoadLibrary(
    'csbiginteger/dotnet/bin/Release/netstandard2.0/publish/csbiginteger.dll',
    'net')

biglib = net.lib.csbiglib.BigIntegerLib()

z = biglib.zero()
print(bytearray(z.ToByteArray()))

m1 = biglib.from_int32(-1)
print(bytearray(m1.ToByteArray()))

i255 = biglib.from_int32(255)
print(bytearray(i255.ToByteArray()))

b2 = biglib.from_bytes(bytearray(i255.ToByteArray()))
print(biglib.to_int32(b2))

b3 = biglib.from_string("0xff", 16)
print(biglib.to_int32(b3))
Esempio n. 15
0
#!/usr/bin/python3

from msl.loadlib import LoadLibrary

net = LoadLibrary('./bin/Release/netstandard2.0/csbiginteger.dll', 'net')

biglib = net.lib.csbiglib.BigIntegerLib()

z = biglib.zero()
print(bytearray(z.ToByteArray()))

m1 = biglib.from_int32(-1)
print(bytearray(m1.ToByteArray()))

i255 = biglib.from_int32(255)
print(bytearray(i255.ToByteArray()))

b2 = biglib.from_bytes(bytearray(i255.ToByteArray()))
print(biglib.to_int32(b2))

b3 = biglib.from_string("0xff", 16)
print(biglib.to_int32(b3))

print(biglib.to_string(b3, 16))
print(biglib.to_string(b3, 10))
print(bytearray(biglib.to_bytes(b3)))
Esempio n. 16
0
 def load_library(self):
     return LoadLibrary(prog_id, 'activex').lib.IsSoundCardEnabled()
Esempio n. 17
0
"""
Checks that running a script with pythonw.exe does not
1) create a new console
2) the console that pythonw.exe is executing on does not "flash"
"""
import os
import sys

# make sure that msl.loadlib is importable
path = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
sys.path.insert(0, path)

from msl.loadlib import LoadLibrary
from msl.examples.loadlib import (
    EXAMPLES_DIR,
    Cpp64,
)

if os.path.basename(sys.executable) != 'pythonw.exe':
    raise RuntimeError('Must run this script using,\n'
                       '  pythonw.exe ' + __file__)

with LoadLibrary(os.path.join(EXAMPLES_DIR, 'Trig.class')) as java:
    pass

with Cpp64():
    pass
Esempio n. 18
0
 def __init__(self, path, libtype, host, port, quiet):
     HTTPServer.__init__(self, (host, int(port)), RequestHandler)
     self.quiet = quiet
     self._library = LoadLibrary(path, libtype)