pylablib.core.devio package

Submodules

pylablib.core.devio.SCPI module

class pylablib.core.devio.SCPI.SCPIDevice(conn, term_write=None, term_read=None, wait_callback=None, backend='auto', backend_defaults=None, failsafe=None, timeout=None, backend_params=None)[source]

Bases: pylablib.core.devio.comm_backend.ICommBackendWrapper

A base class for a device controlled with the usual SCPI syntax.

Implements two functions:
  • deals with composing and parsing of standard SCPI commands and simplifying repetitive property access routines
  • implements automatic re-sending and reconnecting on communication failures (fail-safe mode)
Parameters:
  • conn – Connection parameters (depend on the backend). Can also be an opened comm_backend.IDeviceCommBackend class for a custom backend.
  • term_write (str) – Line terminator for writing operations.
  • wait_callback (callable) – A function to be called periodically (every 300ms by default) while waiting for operations to complete.
  • backend (str) – Connection backend (e.g., 'serial' or 'visa').
  • backend_defaults – if not None, specifies a dictionary {backend: params} with default connection parameters (depending on the backend), which are added to conn
  • failsafe (bool) – If True, the device is working in a fail-safe mode: if an operation times out, attempt to repeat it several times before raising error. If None, use the class value _default_failsafe (False by default).
  • timeout (float) – Default timeout (in seconds).
Error

alias of pylablib.core.devio.base.DeviceError

ReraiseError = None
BackendError

alias of pylablib.core.devio.comm_backend.DeviceBackendError

reconnect(new_instrument=True, ignore_error=True)[source]

Remake the connection.

If new_instrument==True, create a new backend instance. If ignore_error==True, ignore errors on closing.

sleep(delay)[source]

Wait for delay seconds

using_write_buffer()[source]

Context manager for using a write buffer.

While it’s active, all the consecutive write() operations are bundled together with ; delimiter. The actual write is performed at the read()/ask() operation or at the end of the block.

get_id(timeout=None)[source]

Get the device IDN. (query SCPI '*IDN?' command)

reset()[source]

Reset the device (by default, "*RST" command)

get_esr(timeout=None)[source]

Get the device status register (by default, "*ESR?" command)

wait_sync(timeout=None, wait_callback=None)[source]

Pause execution of the script until device overlapped commands (e.g., taking sweeps) are complete.

timeout and wait_callback override default constructor parameters.

wait_dev()[source]

Pause execution of the device commands until device overlapped commands (e.g., taking sweeps) are complete.

Note that the code execution is not paused.

wait(wait_type='sync', timeout=None, wait_callback=None)[source]

Pause execution until device overlapped commands are complete.

wait_type is either 'sync' (perform wait_sync()), 'dev' (perform wait_dev()) or 'none' (do nothing).

static get_arg_type(arg)[source]

Autodetect argument type

write(msg, arg=None, arg_type=None, unit=None, bool_selector=None, wait_sync=None, read_echo=False, read_echo_delay=0.0)[source]

Send a command.

Parameters:
  • msg (str) – Text message.
  • arg – Optional argument to append in the end. If a list of arguments is supplied, the result is joined with ",".
  • arg_type (str) – Argument type. Can be 'raw' (in which case data is sent raw), 'string', 'int', 'float', 'bool', a format string (such as '{:.3f}') or a list of argument types (for an iterable argument); if format string is used and the argument is a list or a tuple, then it is expanded as a list of arguments (e.g., arg_type='{0};{1}' with arg=[1,2] will produce a string '1;2'); if a list of types is used, each element of arg is converted using the corresponding type, and the result is joined with ",".
  • unit (str) – If not None, use it as a unit to append after the value.
  • bool_selector (tuple) – A tuple (false_value, true_value) of two strings to represent bool argument; by default, use ._bool_selector attribute.
  • wait_sync – if True, append the sync command (specified as ._wait_sync_comm attribute, "*OPC?" by default) after the message and pause the execution command is complete; useful in long set operations, where the device might ignore later inputs until the current command is complete; if None, use the class default ._default_write_sync attribute (False by default).
  • read_echo (bool) – If True, read a single line after write.
  • read_echo_delay (float) – The delay between write and read if read_echo==True.
read(data_type='string', timeout=None)[source]

Read data from the device.

data_type determines the type of the data. Can be 'raw' (just raw data), 'string' (with trailing and leading spaces stripped), 'int', 'float', 'bool' (interprets 0 or 'off' as False, anything else as True), 'value' (returns tuple (value, unit), where value is float), a callable (return the result of this callable applied to the string value), a dictionary (return the stored value corresponding to the string value, or to the value converted into integer if the string value is not present), or a list of data types (the result is treated as a list of values with the given types separated by commas). timeout overrides the default value.

class NoParameterCaller(device, kind)

Bases: object

Class to simplify calling functions without a parameter

ask(msg, data_type='string', delay=0.0, timeout=None, read_echo=False)[source]

Write a message and read a reply.

msg is the query message, delay is the delay between write and read. Other parameters are the same as in read(). If read_echo==True, assume that the device first echoes the input and skip it.

close()

Close the backend

get_device_variable(key)

Get the value of a settings, status, or full info parameter

get_full_info(include=0)

Get dict {name: value} containing full device information (including status and settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_full_status(include=0)

Get dict {name: value} containing the device status (including settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_settings(include=0)

Get dict {name: value} containing all the device settings.

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

is_opened()

Check if the device is connected

lock(timeout=None)

Lock the access to the device from other threads/processes (isn’t necessarily implemented)

locking(timeout=None)

Context manager for lock & unlock

open()

Open the backend

set_device_variable(key, value)

Set the value of a settings parameter

unlock()

Unlock the access to the device from other threads/processes (isn’t necessarily implemented)

flush(one_line=False)[source]

Flush the read buffer (read all the available data and return the number of bytes read).

If one_line==True, read only a single line.

read_binary_array_data(include_header=False, timeout=None, flush_term=True)[source]

Read a binary data in the from the device.

The data assumes the standard binary transfer header consisting of "#" symbol, then a single digit with the size of the length string, then the length string containing the length of the binary data (in bytes). If include_header==True, return the data with the header; otherwise, return only the content. If flush_term==True, flush the following line to skip terminator characters after the binary data, which are added by some devices. timeout overrides the default value.

static parse_array_data(data, fmt, include_header=False)[source]

Parse the data returned by the device. fmt is DataFormat description in numpy format (e.g., "<u2").

If include_header==True, the data is assumed to be in a (somewhat) standard SCPI format: b'#', then a single digit s denoting length of the size block, then s digits denoting length of the data (in bytes) followed by the actual data. Otherwise (include_header==False), assume that the header is already removed.

apply_settings(settings)[source]

Apply the settings.

settings is a dict {name: value} of the available device settings. Non-applicable settings are ignored.

pylablib.core.devio.backend_logger module

class pylablib.core.devio.backend_logger.BackendLogger(path)[source]

Bases: object

Backend logger.

Receives log requests from backends and stores them in a predefined file.

Parameters:path – path to save the log
start(header)[source]

Start logging section

stop()[source]

Stop logging section

section(header)[source]

Context manager for operations within a header

log(operation, value)[source]

Log the operation

pylablib.core.devio.backend_logger.load_logfile(path)[source]

Load backend log file.

Return a list of tuples [(header, section)], where header is the header name, and section is the list [(op, value)] with operations ("r", "w", or "e") nd corresponding values.

pylablib.core.devio.base module

exception pylablib.core.devio.base.DeviceError[source]

Bases: RuntimeError

Generic device communication error

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

pylablib.core.devio.comm_backend module

Routines for defining a unified interface across multiple backends.

exception pylablib.core.devio.comm_backend.DeviceBackendError(exc)[source]

Bases: pylablib.core.devio.base.DeviceError

Generic exception relaying a backend error

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

pylablib.core.devio.comm_backend.reraise(func)[source]

Wrapper for a backend method which intercepts backend exceptions and re-emits them as a subclass of DeviceBackendError defined in the class

pylablib.core.devio.comm_backend.logerror(func)[source]

Wrapper for a backend method which logs if any errors escaped

class pylablib.core.devio.comm_backend.IDeviceCommBackend(conn, timeout=None, term_write=None, term_read=None, datatype='auto', reraise_error=None)[source]

Bases: object

An abstract class for a device communication backend.

Connection is automatically opened on creation.

Parameters:
  • conn – Connection parameters (depend on the backend).
  • timeout (float) – Default timeout (in seconds).
  • term_write (str) – Line terminator for writing operations.
  • term_read (str) – Line terminator for reading operations.
  • datatype (str) – Type of the returned data; can be "bytes" (return bytes object), "str" (return str object), or "auto" (default Python result: str in Python 2 and bytes in Python 3)
  • reraise_error – if not None, specifies an error to be re-raised on any backend exception (by default, use backend-specific error); should be a subclass of DeviceBackendError.
BackendError = None

Base class for the errors raised by the backend operations

Error

alias of DeviceBackendError

classmethod combine_conn(conn1, conn2)[source]

Combined two connection parameters into a single dictionary (conn1 overrides conn2)

classmethod get_backend_name()[source]

Get string representation of the backend (e.g., "serial", "visa", or "network")

open()[source]

Open the connection

close()[source]

Close the connection

is_opened()[source]

Check if the device is connected

lock(timeout=None)[source]

Lock the access to the device from other threads/processes (isn’t necessarily implemented)

unlock()[source]

Unlock the access to the device from other threads/processes (isn’t necessarily implemented)

locking(timeout=None)[source]

Context manager for lock & unlock

setup_cooldown(**kwargs)[source]

Setup cooldown times for various operations.

The arguments are of the form kind=value, where value is the cooldown time (in seconds), and kind is the operation kind (common kinds are open, close, read, write, timeout, and flush). kind can also be default (default value for all kind), or all (reset all cooldown values to this value). The cooldowns of the given kinds are usually called after the corresponding operation (it is necessary for some devices, otherwise the communication can freeze or crush). Default cooldown values are specified by _default_operation_cooldown class attribute dictionary.

cooldown(kind='default')[source]

Cooldown between the operations.

kind specifies the operation kind (common kinds are open, close, read, write, timeout, and flush); "default" corresponds to the default cooldown (usually, specified as 0). Called automatically by various backend operations, so usually there is no need to call explicitly.

set_timeout(timeout)[source]

Set operations timeout (in seconds)

get_timeout()[source]

Get operations timeout (in seconds)

using_timeout(timeout=None)[source]

Context manager for usage of a different timeout inside a block

readline(remove_term=True, timeout=None, skip_empty=True)[source]

Read a single line from the device.

Parameters:
  • remove_term (bool) – If True, remove terminal characters from the result.
  • timeout – Operation timeout. If None, use the default device timeout.
  • skip_empty (bool) – If True, ignore empty lines (works only for remove_term==True).
readlines(lines_num, remove_term=True, timeout=None, skip_empty=True)[source]

Read multiple lines from the device.

Parameters are the same as in readline().

read(size=None)[source]

Read data from the device.

If size is not None, read size bytes (the standard timeout applies); otherwise, read all available data (return immediately).

flush_read()[source]

Flush the device output (read all the available data; return the number of bytes read)

write(data, flush=True, read_echo=False, read_echo_delay=0, read_echo_lines=1)[source]

Write data to the device.

If flush==True, flush the write buffer. If read_echo==True, wait for read_echo_delay seconds and then perform readline() (read_echo_lines times).

ask(query, delay=0.0, read_all=False)[source]

Perform a write followed by a read, with delay in between.

If read_all==True, read all the available data; otherwise, read a single line.

static list_resources(desc=False)[source]

List all available resources for this backend.

If desc==False, return list of connections (usually strings or tuples), which can be used to connect to the device. Otherwise, return a list of descriptions, which have more info, but can be backend-dependent.

Might not be implemented (depending on the backend), in which case returns None.

pylablib.core.devio.comm_backend.remove_longest_term(msg, terms)[source]

Remove the longest terminator among terms from the end of the message.

exception pylablib.core.devio.comm_backend.DeviceVisaError(exc)[source]

Bases: pylablib.core.devio.comm_backend.DeviceBackendError

Visa backend operation error

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class pylablib.core.devio.comm_backend.VisaDeviceBackend(conn, timeout=10.0, term_write=None, term_read=None, do_lock=None, datatype='auto', reraise_error=None)[source]

Bases: pylablib.core.devio.comm_backend.IDeviceCommBackend

NIVisa backend (via pyVISA).

Connection is automatically opened on creation.

Parameters:
  • conn (str) – Connection string.
  • timeout (float) – Default timeout (in seconds).
  • term_write (str) – Line terminator for writing operations; appended to the data
  • term_read (str) – Line terminator for reading operations (specifies when readline() stops).
  • do_lock (bool) – If True, employ locking operations; otherwise, locking function does nothing.
  • datatype (str) – Type of the returned data; can be "bytes" (return bytes object), "str" (return str object), or "auto" (default Python result: str in Python 2 and bytes in Python 3)
  • reraise_error – if not None, specifies an error to be re-raised on any backend exception (by default, use backend-specific error); should be a subclass of DeviceBackendError.
BackendError

alias of builtins.object

Error

alias of DeviceVisaError

static list_resources(desc=False)[source]

List all available resources for this backend.

If desc==False, return list of connections (usually strings or tuples), which can be used to connect to the device. Otherwise, return a list of descriptions, which have more info, but can be backend-dependent.

Might not be implemented (depending on the backend), in which case returns None.

open()[source]

Open the connection

close()[source]

Close the connection

is_opened()[source]

Check if the device is connected

lock(timeout=None)[source]

Lock the access to the device from other threads/processes

unlock()[source]

Unlock the access to the device from other threads/processes

locking(timeout=None)[source]

Context manager for lock & unlock

set_timeout(timeout)[source]

Set operations timeout (in seconds)

get_timeout()[source]

Get operations timeout (in seconds)

readline(remove_term=True, timeout=None, skip_empty=True)[source]

Read a single line from the device.

Parameters:
  • remove_term (bool) – If True, remove terminal characters from the result.
  • timeout – Operation timeout. If None, use the default device timeout.
  • skip_empty (bool) – If True, ignore empty lines (works only for remove_term==True).
read(size=None)[source]

Read data from the device.

If size is not None, read size bytes (the standard timeout applies); otherwise, read all available data (return immediately).

write(data, flush=True, read_echo=False, read_echo_delay=0, read_echo_lines=1)[source]

Write data to the device.

If read_echo==True, wait for read_echo_delay seconds and then perform readline() (read_echo_lines times). flush parameter is ignored.

ask(query, delay=0.0, read_all=False)

Perform a write followed by a read, with delay in between.

If read_all==True, read all the available data; otherwise, read a single line.

classmethod combine_conn(conn1, conn2)

Combined two connection parameters into a single dictionary (conn1 overrides conn2)

cooldown(kind='default')

Cooldown between the operations.

kind specifies the operation kind (common kinds are open, close, read, write, timeout, and flush); "default" corresponds to the default cooldown (usually, specified as 0). Called automatically by various backend operations, so usually there is no need to call explicitly.

flush_read()

Flush the device output (read all the available data; return the number of bytes read)

classmethod get_backend_name()

Get string representation of the backend (e.g., "serial", "visa", or "network")

readlines(lines_num, remove_term=True, timeout=None, skip_empty=True)

Read multiple lines from the device.

Parameters are the same as in readline().

setup_cooldown(**kwargs)

Setup cooldown times for various operations.

The arguments are of the form kind=value, where value is the cooldown time (in seconds), and kind is the operation kind (common kinds are open, close, read, write, timeout, and flush). kind can also be default (default value for all kind), or all (reset all cooldown values to this value). The cooldowns of the given kinds are usually called after the corresponding operation (it is necessary for some devices, otherwise the communication can freeze or crush). Default cooldown values are specified by _default_operation_cooldown class attribute dictionary.

using_timeout(timeout=None)

Context manager for usage of a different timeout inside a block

exception pylablib.core.devio.comm_backend.DeviceSerialError(exc)[source]

Bases: pylablib.core.devio.comm_backend.DeviceBackendError

Serial backend operation error

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class pylablib.core.devio.comm_backend.SerialDeviceBackend(conn, timeout=10.0, term_write=None, term_read=None, connect_on_operation=False, open_retry_times=3, no_dtrrts=False, datatype='auto', reraise_error=None)[source]

Bases: pylablib.core.devio.comm_backend.IDeviceCommBackend

Serial backend (via pySerial).

Connection is automatically opened on creation.

Parameters:
  • conn – Connection parameters. Can be either a string (for a port), or a list/tuple (port, baudrate, bytesize, parity, stopbits, xonxoff, rtscts, dsrdtr) supplied to the serial connection (default is ('COM1',19200,8,'N',1,0,0,0)), or a dict with the same parameters.
  • timeout (float) – Default timeout (in seconds).
  • term_write (str) – Line terminator for writing operations; appended to the data
  • term_read (str) – List of possible single-char terminator for reading operations (specifies when readline() stops).
  • connect_on_operation (bool) – If True, the connection is normally closed, and is opened only on the operations (normally two processes can’t be simultaneously connected to the same device).
  • open_retry_times (int) – Number of times the connection is attempted before giving up.
  • no_dtrrts (bool) – If True, turn off DTR and RTS status lines before opening (e.g., turns off reset-on-connection for Arduino controllers).
  • datatype (str) – Type of the returned data; can be "bytes" (return bytes object), "str" (return str object), or "auto" (default Python result: str in Python 2 and bytes in Python 3)
  • reraise_error – if not None, specifies an error to be re-raised on any backend exception (by default, use backend-specific error); should be a subclass of DeviceBackendError.
BackendError

alias of builtins.object

Error

alias of DeviceSerialError

open()[source]

Open the connection

close()[source]

Close the connection

is_opened()[source]

Check if the device is connected

single_op()[source]

Context manager for a single operation.

If connect_on_operation==True during creation, wrapping several command in single_op prevents the connection from being closed and reopened between the operations (only opened in the beginning and closed in the end).

set_timeout(timeout)[source]

Set operations timeout (in seconds)

get_timeout()[source]

Get operations timeout (in seconds)

readline(remove_term=True, timeout=None, skip_empty=True, error_on_timeout=True)[source]

Read a single line from the device.

Parameters:
  • remove_term (bool) – If True, remove terminal characters from the result.
  • timeout – Operation timeout. If None, use the default device timeout.
  • skip_empty (bool) – If True, ignore empty lines (works only for remove_term==True).
  • error_on_timeout (bool) – If False, return an incomplete line instead of raising the error on timeout.
read(size=None)[source]

Read data from the device.

If size is not None, read size bytes (usual timeout applies); otherwise, read all available data (return immediately).

read_multichar_term(term, remove_term=True, timeout=None, error_on_timeout=True)[source]

Read a single line with multiple possible terminators.

Parameters:
  • term – Either a string (single multi-char terminator) or a list of strings (multiple terminators).
  • remove_term (bool) – If True, remove terminal characters from the result.
  • timeout – Operation timeout. If None, use the default device timeout.
  • error_on_timeout (bool) – If False, return an incomplete line instead of raising the error on timeout.
write(data, flush=True, read_echo=False, read_echo_delay=0, read_echo_lines=1)[source]

Write data to the device.

If flush==True, flush the write buffer. If read_echo==True, wait for read_echo_delay seconds and then perform readline() (read_echo_lines times).

static list_resources(desc=False)[source]

List all available resources for this backend.

If desc==False, return list of connections (usually strings or tuples), which can be used to connect to the device. Otherwise, return a list of descriptions, which have more info, but can be backend-dependent.

Might not be implemented (depending on the backend), in which case returns None.

ask(query, delay=0.0, read_all=False)

Perform a write followed by a read, with delay in between.

If read_all==True, read all the available data; otherwise, read a single line.

classmethod combine_conn(conn1, conn2)

Combined two connection parameters into a single dictionary (conn1 overrides conn2)

cooldown(kind='default')

Cooldown between the operations.

kind specifies the operation kind (common kinds are open, close, read, write, timeout, and flush); "default" corresponds to the default cooldown (usually, specified as 0). Called automatically by various backend operations, so usually there is no need to call explicitly.

flush_read()

Flush the device output (read all the available data; return the number of bytes read)

classmethod get_backend_name()

Get string representation of the backend (e.g., "serial", "visa", or "network")

lock(timeout=None)

Lock the access to the device from other threads/processes (isn’t necessarily implemented)

locking(timeout=None)

Context manager for lock & unlock

readlines(lines_num, remove_term=True, timeout=None, skip_empty=True)

Read multiple lines from the device.

Parameters are the same as in readline().

setup_cooldown(**kwargs)

Setup cooldown times for various operations.

The arguments are of the form kind=value, where value is the cooldown time (in seconds), and kind is the operation kind (common kinds are open, close, read, write, timeout, and flush). kind can also be default (default value for all kind), or all (reset all cooldown values to this value). The cooldowns of the given kinds are usually called after the corresponding operation (it is necessary for some devices, otherwise the communication can freeze or crush). Default cooldown values are specified by _default_operation_cooldown class attribute dictionary.

unlock()

Unlock the access to the device from other threads/processes (isn’t necessarily implemented)

using_timeout(timeout=None)

Context manager for usage of a different timeout inside a block

exception pylablib.core.devio.comm_backend.DeviceFT232Error(exc)[source]

Bases: pylablib.core.devio.comm_backend.DeviceBackendError

FT232 backend operation error

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class pylablib.core.devio.comm_backend.FT232DeviceBackend(conn, timeout=10.0, term_write=None, term_read=None, open_retry_times=3, datatype='auto', reraise_error=None)[source]

Bases: pylablib.core.devio.comm_backend.IDeviceCommBackend

FT232 backend (via pyft232).

Connection is automatically opened on creation.

Parameters:
  • conn – Connection parameters. Can be either a string (for a port), or a list/tuple (port, baudrate, bytesize, parity, stopbits, xonxoff, rtscts) supplied to the serial connection (default is ('COM1',19200,8,'N',1,0,0,0)), or a dict with the same parameters.
  • timeout (float) – Default timeout (in seconds).
  • term_write (str) – Line terminator for writing operations; appended to the data
  • term_read (str) – List of possible single-char terminator for reading operations (specifies when readline() stops).
  • open_retry_times (int) – Number of times the connection is attempted before giving up.
  • datatype (str) – Type of the returned data; can be "bytes" (return bytes object), "str" (return str object), or "auto" (default Python result: str in Python 2 and bytes in Python 3)
  • reraise_error – if not None, specifies an error to be re-raised on any backend exception (by default, use backend-specific error); should be a subclass of DeviceBackendError.
BackendError

alias of builtins.object

Error

alias of DeviceFT232Error

open()[source]

Open the connection

close()[source]

Close the connection

is_opened()[source]

Check if the device is connected

single_op()[source]

Context manager for a single operation.

Does nothing.

set_timeout(timeout)[source]

Set operations timeout (in seconds)

get_timeout()[source]

Get operations timeout (in seconds)

readline(remove_term=True, timeout=None, skip_empty=True, error_on_timeout=True)[source]

Read a single line from the device.

Parameters:
  • remove_term (bool) – If True, remove terminal characters from the result.
  • timeout – Operation timeout. If None, use the default device timeout.
  • skip_empty (bool) – If True, ignore empty lines (works only for remove_term==True).
  • error_on_timeout (bool) – If False, return an incomplete line instead of raising the error on timeout.
read(size=None)[source]

Read data from the device.

If size is not None, read size bytes (usual timeout applies); otherwise, read all available data (return immediately).

read_multichar_term(term, remove_term=True, timeout=None, error_on_timeout=True)[source]

Read a single line with multiple possible terminators.

Parameters:
  • term – Either a string (single multi-char terminator) or a list of strings (multiple terminators).
  • remove_term (bool) – If True, remove terminal characters from the result.
  • timeout – Operation timeout. If None, use the default device timeout.
  • error_on_timeout (bool) – If False, return an incomplete line instead of raising the error on timeout.
write(data, flush=True, read_echo=False, read_echo_delay=0, read_echo_lines=1)[source]

Write data to the device.

If flush==True, flush the write buffer. If read_echo==True, wait for read_echo_delay seconds and then perform readline() (read_echo_lines times).

static list_resources(desc=False)[source]

List all available resources for this backend.

If desc==False, return list of connections (usually strings or tuples), which can be used to connect to the device. Otherwise, return a list of descriptions, which have more info, but can be backend-dependent.

Might not be implemented (depending on the backend), in which case returns None.

ask(query, delay=0.0, read_all=False)

Perform a write followed by a read, with delay in between.

If read_all==True, read all the available data; otherwise, read a single line.

classmethod combine_conn(conn1, conn2)

Combined two connection parameters into a single dictionary (conn1 overrides conn2)

cooldown(kind='default')

Cooldown between the operations.

kind specifies the operation kind (common kinds are open, close, read, write, timeout, and flush); "default" corresponds to the default cooldown (usually, specified as 0). Called automatically by various backend operations, so usually there is no need to call explicitly.

flush_read()

Flush the device output (read all the available data; return the number of bytes read)

classmethod get_backend_name()

Get string representation of the backend (e.g., "serial", "visa", or "network")

lock(timeout=None)

Lock the access to the device from other threads/processes (isn’t necessarily implemented)

locking(timeout=None)

Context manager for lock & unlock

readlines(lines_num, remove_term=True, timeout=None, skip_empty=True)

Read multiple lines from the device.

Parameters are the same as in readline().

setup_cooldown(**kwargs)

Setup cooldown times for various operations.

The arguments are of the form kind=value, where value is the cooldown time (in seconds), and kind is the operation kind (common kinds are open, close, read, write, timeout, and flush). kind can also be default (default value for all kind), or all (reset all cooldown values to this value). The cooldowns of the given kinds are usually called after the corresponding operation (it is necessary for some devices, otherwise the communication can freeze or crush). Default cooldown values are specified by _default_operation_cooldown class attribute dictionary.

unlock()

Unlock the access to the device from other threads/processes (isn’t necessarily implemented)

using_timeout(timeout=None)

Context manager for usage of a different timeout inside a block

exception pylablib.core.devio.comm_backend.DeviceNetworkError(exc)[source]

Bases: pylablib.core.devio.comm_backend.DeviceBackendError

Network backend operation error

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class pylablib.core.devio.comm_backend.NetworkDeviceBackend(conn, timeout=10.0, term_write=None, term_read=None, datatype='auto', reraise_error=None)[source]

Bases: pylablib.core.devio.comm_backend.IDeviceCommBackend

Serial backend (via pySerial).

Connection is automatically opened on creation.

Parameters:
  • conn – Connection parameters. Can be either a string "IP:port" (e.g., "127.0.0.1:80"), or a tuple (IP,port), where IP is a string and port is a number.
  • timeout (float) – Default timeout (in seconds).
  • term_write (str) – Line terminator for writing operations; appended to the data
  • term_read (str) – List of possible single-char terminator for reading operations (specifies when readline() stops).
  • datatype (str) – Type of the returned data; can be "bytes" (return bytes object), "str" (return str object), or "auto" (default Python result: str in Python 2 and bytes in Python 3)
  • reraise_error – if not None, specifies an error to be re-raised on any backend exception (by default, use backend-specific error); should be a subclass of DeviceBackendError.

Note

If term_read is a string, its behavior is different from the VISA backend: instead of being a multi-char terminator it is assumed to be a set of single-char terminators. If multi-char terminator is required, term_read should be a single-element list instead of a string.

BackendError

alias of builtins.OSError

Error

alias of DeviceNetworkError

open()[source]

Open the connection

close()[source]

Close the connection

is_opened()[source]

Check if the device is connected

set_timeout(timeout)[source]

Set operations timeout (in seconds)

get_timeout()[source]

Get operations timeout (in seconds)

readline(remove_term=True, timeout=None, skip_empty=True)[source]

Read a single line from the device.

Parameters:
  • remove_term (bool) – If True, remove terminal characters from the result.
  • timeout – Operation timeout. If None, use the default device timeout.
  • skip_empty (bool) – If True, ignore empty lines (works only for remove_term==True).
read(size=None)[source]

Read data from the device.

If size is not None, read size bytes (usual timeout applies); otherwise, read all available data (return immediately).

read_multichar_term(term, remove_term=True, timeout=None)[source]

Read a single line with multiple possible terminators.

Parameters:
  • term – Either a string (single multi-char terminator) or a list of strings (multiple terminators).
  • remove_term (bool) – If True, remove terminal characters from the result.
  • timeout – Operation timeout. If None, use the default device timeout.
write(data, flush=True, read_echo=False, read_echo_delay=0, read_echo_lines=1)[source]

Write data to the device.

If read_echo==True, wait for read_echo_delay seconds and then perform readline() (read_echo_lines times). flush parameter is ignored.

ask(query, delay=0.0, read_all=False)

Perform a write followed by a read, with delay in between.

If read_all==True, read all the available data; otherwise, read a single line.

classmethod combine_conn(conn1, conn2)

Combined two connection parameters into a single dictionary (conn1 overrides conn2)

cooldown(kind='default')

Cooldown between the operations.

kind specifies the operation kind (common kinds are open, close, read, write, timeout, and flush); "default" corresponds to the default cooldown (usually, specified as 0). Called automatically by various backend operations, so usually there is no need to call explicitly.

flush_read()

Flush the device output (read all the available data; return the number of bytes read)

classmethod get_backend_name()

Get string representation of the backend (e.g., "serial", "visa", or "network")

static list_resources(desc=False)

List all available resources for this backend.

If desc==False, return list of connections (usually strings or tuples), which can be used to connect to the device. Otherwise, return a list of descriptions, which have more info, but can be backend-dependent.

Might not be implemented (depending on the backend), in which case returns None.

lock(timeout=None)

Lock the access to the device from other threads/processes (isn’t necessarily implemented)

locking(timeout=None)

Context manager for lock & unlock

readlines(lines_num, remove_term=True, timeout=None, skip_empty=True)

Read multiple lines from the device.

Parameters are the same as in readline().

setup_cooldown(**kwargs)

Setup cooldown times for various operations.

The arguments are of the form kind=value, where value is the cooldown time (in seconds), and kind is the operation kind (common kinds are open, close, read, write, timeout, and flush). kind can also be default (default value for all kind), or all (reset all cooldown values to this value). The cooldowns of the given kinds are usually called after the corresponding operation (it is necessary for some devices, otherwise the communication can freeze or crush). Default cooldown values are specified by _default_operation_cooldown class attribute dictionary.

unlock()

Unlock the access to the device from other threads/processes (isn’t necessarily implemented)

using_timeout(timeout=None)

Context manager for usage of a different timeout inside a block

exception pylablib.core.devio.comm_backend.DeviceUSBError(exc)[source]

Bases: pylablib.core.devio.comm_backend.DeviceBackendError

USB backend operation error

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class pylablib.core.devio.comm_backend.PyUSBDeviceBackend(conn, timeout=10.0, term_write=None, term_read=None, check_read_size=True, datatype='auto', reraise_error=None)[source]

Bases: pylablib.core.devio.comm_backend.IDeviceCommBackend

USB backend (via PyUSB package).

Connection is automatically opened on creation.

Parameters:
  • conn – Connection parameters. Can be either a string (for a port), or a list/tuple (vendorID, productID, index, endpoint_read, endpoint_write, backend) supplied to the connection (default is (0x0000,0x0000,0,0x00,0x01,'libusb1'), which is invalid for most devices), or a dict with the same parameters. vendorID and productID specify device kind, index is an integer index (starting from zero) of the device among several identical (i.e., with the same ids) ones, and endpoint_read and endpoint_write specify connection endpoints for the specific device.
  • timeout (float) – Default timeout (in seconds).
  • term_write (str) – Line terminator for writing operations; appended to the data
  • term_read (str) – List of possible single-char terminator for reading operations (specifies when readline() stops).
  • datatype (str) – Type of the returned data; can be "bytes" (return bytes object), "str" (return str object), or "auto" (default Python result: str in Python 2 and bytes in Python 3)
  • reraise_error – if not None, specifies an error to be re-raised on any backend exception (by default, use backend-specific error); should be a subclass of DeviceBackendError.
BackendError

alias of usb.core.USBError

Error

alias of DeviceUSBError

open()[source]

Open the connection

close()[source]

Close the connection

is_opened()[source]

Check if the device is connected

set_timeout(timeout)[source]

Set operations timeout (in seconds)

get_timeout()[source]

Get operations timeout (in seconds)

readline(remove_term=True, timeout=None, skip_empty=True, error_on_timeout=True)[source]

Read a single line from the device.

Parameters:
  • remove_term (bool) – If True, remove terminal characters from the result.
  • timeout – Operation timeout. If None, use the default device timeout.
  • skip_empty (bool) – If True, ignore empty lines (works only for remove_term==True).
  • error_on_timeout (bool) – If False, return an incomplete line instead of raising the error on timeout.
read(size=None, max_read_size=65536)[source]

Read data from the device.

If size is not None, read size bytes (usual timeout applies); otherwise, read all available data (return immediately).

read_multichar_term(term, remove_term=True, timeout=None, error_on_timeout=True)[source]

Read a single line with multiple possible terminators.

Parameters:
  • term – Either a string (single multi-char terminator) or a list of strings (multiple terminators).
  • remove_term (bool) – If True, remove terminal characters from the result.
  • timeout – Operation timeout. If None, use the default device timeout.
  • error_on_timeout (bool) – If False, return an incomplete line instead of raising the error on timeout.
write(data, flush=True, read_echo=False, read_echo_delay=0, read_echo_lines=1)[source]

Write data to the device.

If read_echo==True, wait for read_echo_delay seconds and then perform readline() (read_echo_lines times). flush parameter is ignored.

static list_resources(desc=False, **kwargs)[source]

List all available resources for this backend.

If desc==False, return list of connections (usually strings or tuples), which can be used to connect to the device. Otherwise, return a list of descriptions, which have more info, but can be backend-dependent.

Might not be implemented (depending on the backend), in which case returns None.

ask(query, delay=0.0, read_all=False)

Perform a write followed by a read, with delay in between.

If read_all==True, read all the available data; otherwise, read a single line.

classmethod combine_conn(conn1, conn2)

Combined two connection parameters into a single dictionary (conn1 overrides conn2)

cooldown(kind='default')

Cooldown between the operations.

kind specifies the operation kind (common kinds are open, close, read, write, timeout, and flush); "default" corresponds to the default cooldown (usually, specified as 0). Called automatically by various backend operations, so usually there is no need to call explicitly.

flush_read()

Flush the device output (read all the available data; return the number of bytes read)

classmethod get_backend_name()

Get string representation of the backend (e.g., "serial", "visa", or "network")

lock(timeout=None)

Lock the access to the device from other threads/processes (isn’t necessarily implemented)

locking(timeout=None)

Context manager for lock & unlock

readlines(lines_num, remove_term=True, timeout=None, skip_empty=True)

Read multiple lines from the device.

Parameters are the same as in readline().

setup_cooldown(**kwargs)

Setup cooldown times for various operations.

The arguments are of the form kind=value, where value is the cooldown time (in seconds), and kind is the operation kind (common kinds are open, close, read, write, timeout, and flush). kind can also be default (default value for all kind), or all (reset all cooldown values to this value). The cooldowns of the given kinds are usually called after the corresponding operation (it is necessary for some devices, otherwise the communication can freeze or crush). Default cooldown values are specified by _default_operation_cooldown class attribute dictionary.

unlock()

Unlock the access to the device from other threads/processes (isn’t necessarily implemented)

using_timeout(timeout=None)

Context manager for usage of a different timeout inside a block

exception pylablib.core.devio.comm_backend.DeviceRecordedError(exc)[source]

Bases: pylablib.core.devio.comm_backend.DeviceBackendError

Recorded backend operation error

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class pylablib.core.devio.comm_backend.RecordedDeviceBackend(conn, datatype='auto', reraise_error=None)[source]

Bases: pylablib.core.devio.comm_backend.IDeviceCommBackend

Recorded backend.

Connection is automatically opened on creation.

Parameters:
  • conn – connection parameters (recorded log path)
  • datatype (str) – Type of the returned data; can be "bytes" (return bytes object), "str" (return str object), or "auto" (default Python result: str in Python 2 and bytes in Python 3)
  • reraise_error – if not None, specifies an error to be re-raised on any backend exception (by default, use backend-specific error); should be a subclass of DeviceBackendError.
BackendError

alias of builtins.OSError

Error

alias of DeviceRecordedError

open()[source]

Open the connection

close()[source]

Close the connection

is_opened()[source]

Check if the device is connected

start(header)[source]

Start recorded section

stop()[source]

Stop logging section

section(header)[source]
readline(remove_term=True, timeout=None, skip_empty=True)[source]

Read a single line from the device.

Parameters:
  • remove_term (bool) – If True, remove terminal characters from the result.
  • timeout – Operation timeout. If None, use the default device timeout.
  • skip_empty (bool) – If True, ignore empty lines (works only for remove_term==True).
read(size=None)[source]

Read data from the device.

If size is not None, read size bytes (usual timeout applies); otherwise, read all available data (return immediately).

write(data, flush=True, read_echo=False, read_echo_delay=0, read_echo_lines=1)[source]

Write data to the device.

If flush==True, flush the write buffer. If read_echo==True, wait for read_echo_delay seconds and then perform readline() (read_echo_lines times).

ask(query, delay=0.0, read_all=False)

Perform a write followed by a read, with delay in between.

If read_all==True, read all the available data; otherwise, read a single line.

classmethod combine_conn(conn1, conn2)

Combined two connection parameters into a single dictionary (conn1 overrides conn2)

cooldown(kind='default')

Cooldown between the operations.

kind specifies the operation kind (common kinds are open, close, read, write, timeout, and flush); "default" corresponds to the default cooldown (usually, specified as 0). Called automatically by various backend operations, so usually there is no need to call explicitly.

flush_read()

Flush the device output (read all the available data; return the number of bytes read)

classmethod get_backend_name()

Get string representation of the backend (e.g., "serial", "visa", or "network")

get_timeout()

Get operations timeout (in seconds)

static list_resources(desc=False)

List all available resources for this backend.

If desc==False, return list of connections (usually strings or tuples), which can be used to connect to the device. Otherwise, return a list of descriptions, which have more info, but can be backend-dependent.

Might not be implemented (depending on the backend), in which case returns None.

lock(timeout=None)

Lock the access to the device from other threads/processes (isn’t necessarily implemented)

locking(timeout=None)

Context manager for lock & unlock

readlines(lines_num, remove_term=True, timeout=None, skip_empty=True)

Read multiple lines from the device.

Parameters are the same as in readline().

set_timeout(timeout)

Set operations timeout (in seconds)

setup_cooldown(**kwargs)

Setup cooldown times for various operations.

The arguments are of the form kind=value, where value is the cooldown time (in seconds), and kind is the operation kind (common kinds are open, close, read, write, timeout, and flush). kind can also be default (default value for all kind), or all (reset all cooldown values to this value). The cooldowns of the given kinds are usually called after the corresponding operation (it is necessary for some devices, otherwise the communication can freeze or crush). Default cooldown values are specified by _default_operation_cooldown class attribute dictionary.

unlock()

Unlock the access to the device from other threads/processes (isn’t necessarily implemented)

using_timeout(timeout=None)

Context manager for usage of a different timeout inside a block

pylablib.core.devio.comm_backend.autodetect_backend(conn, default='visa')[source]

Try to determine the backend by the connection.

default specifies the default backend which is returned if the backend is unclear.

pylablib.core.devio.comm_backend.new_backend(conn, backend='auto', defaults=None, **kwargs)[source]

Build new backend with the supplied parameters.

Parameters:
  • conn – Connection parameters (depend on the backend). Can be simply connection parameters (tuple or dict) for the given backend (e.g., "192.168.0.1" or ("COM1",19200)), a tuple (backend, conn) which specifies both backend and connection (in which case it overrides the supplied backend), or an already opened backend (in which case it is returned as is)
  • backend (str) – Backend type. Available backends are 'auto' (try to autodetect based on the connection), 'visa', 'serial', 'ft232', 'network', and "pyusb". Can also be directly a backend class (more appropriate for custom backends), or a tuple ('auto', backend), which is analogous to 'auto', but it returns the specified backend if the autodetection fails; by default, the fallback backend is 'visa', so 'auto' is exactly the same as ('auto', 'visa').
  • defaults – if not None, specifies a dictionary {backend: params} with default connection parameters (depending on the backend), which are added to the connection parameters
  • **kwargs – parameters sent to the backend.
pylablib.core.devio.comm_backend.backend_error(backend, conn=None)[source]

Return error class corresponding to the current backend.

Like new_backend(), allows setting backend="auto", in which case conn is used to try and autodetect the backend kind (not completely reliable, should be avoided).

pylablib.core.devio.comm_backend.list_backend_resources(backend=None, desc=False)[source]

List all resources for the given backend.

If backend is None, return dictionary {backend: resources} for all available backends. If desc==False, return list of connections (usually strings or tuples), which can be used to connect to the device. Otherwise, return a list of descriptions, which have more info, but can be backend-dependent.

class pylablib.core.devio.comm_backend.ICommBackendWrapper(instr)[source]

Bases: pylablib.core.devio.interface.IDevice

A base class for an instrument using a communication backend.

Parameters:instr – Backend (assumed to be already opened).
class NoParameterCaller(device, kind)

Bases: object

Class to simplify calling functions without a parameter

apply_settings(settings)

Apply the settings.

settings is the dict {name: value} of the device available settings. Non-applicable settings are ignored.

get_device_variable(key)

Get the value of a settings, status, or full info parameter

get_full_info(include=0)

Get dict {name: value} containing full device information (including status and settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_full_status(include=0)

Get dict {name: value} containing the device status (including settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_settings(include=0)

Get dict {name: value} containing all the device settings.

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

set_device_variable(key, value)

Set the value of a settings parameter

open()[source]

Open the backend

close()[source]

Close the backend

is_opened()[source]

Check if the device is connected

lock(timeout=None)[source]

Lock the access to the device from other threads/processes (isn’t necessarily implemented)

unlock()[source]

Unlock the access to the device from other threads/processes (isn’t necessarily implemented)

locking(timeout=None)[source]

Context manager for lock & unlock

pylablib.core.devio.data_format module

Library for binary data encoding/decoding for device communication and dealing with different data format representations in different contexts (numpy, SCPI, etc.).

class pylablib.core.devio.data_format.DataFormat(size, kind, byteorder)[source]

Bases: object

Describes data encoding for device communications.

Parameters:
  • size (int) – Size of a single element (in bytes).
  • kind (str) – Kind of the element. Can be 'i' (integer), 'u' (unsigned integer), 'f' (floating point) or 'ascii' (text representation).
  • byteorder (str) – Byte order: '>' is big-endian (MSB first), '<' is little-endian (LSB first).
flip_byteorder()[source]

Flip byteorder of the description

is_ascii()[source]

Check of the format is textual

static from_desc(desc, str_type='numpy')[source]

Build the format from the string description.

str_type is the description format. Can be 'numpy' (numpy dtype description), 'struct' (struct description) or 'SCPI' (the standard SCPI description).

static from_desc_SCPI(desc, border='norm')[source]

Build the format from the string SCPI description.

border describes byte order (either 'norm' or 'swap').

to_desc(str_type='auto')[source]

Build a description string of this format.

str_type can be 'auto' (similar to 'numpy', but also accepts 'ascii'), 'numpy', 'struct' or 'SCPI' (return tuple (desc, border)).

convert_from_str(data)[source]

Convert the string data into an array

convert_to_str(data, ascii_format='.5f')[source]

Convert the array into a string data.

ascii_format is the str.format() string for textual representation.

pylablib.core.devio.interface module

class pylablib.core.devio.interface.IDevice[source]

Bases: object

A base class for an instrument.

Contains some useful functions for dealing with device settings.

open()[source]

Open the connection

close()[source]

Close the connection

is_opened()[source]

Check if the device is connected

class NoParameterCaller(device, kind)[source]

Bases: object

Class to simplify calling functions without a parameter

get_settings(include=0)[source]

Get dict {name: value} containing all the device settings.

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_full_status(include=0)[source]

Get dict {name: value} containing the device status (including settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_full_info(include=0)[source]

Get dict {name: value} containing full device information (including status and settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

apply_settings(settings)[source]

Apply the settings.

settings is the dict {name: value} of the device available settings. Non-applicable settings are ignored.

get_device_variable(key)[source]

Get the value of a settings, status, or full info parameter

set_device_variable(key, value)[source]

Set the value of a settings parameter

class pylablib.core.devio.interface.IParameterClass(name)[source]

Bases: object

A generic parameter class.

Deals with converting device interface representation and the ‘internal’ representation (e.g., names used in SCPI commands or integer indices). Also responsible for validating the user-passed and device-returned parameters.

Needs to define to methods: __call__ for converting user parameters (‘alias’) into the device parameters (‘value’) and i() for the opposite conversion. In addition, it provides using_device() context manager to temporarily change the device attribute, which can be used by some parameter classes for device-dependent conversions.

Parameters:name – parameter class name; used to match method arguments with corresponding classes.
using_device(device)[source]

Context manager for temporarily changing the device attribute to the given device instance

docstring()[source]

Get a parameter docstring

i(value, device=None)[source]

Convert device parameter value into a corresponding use parameter value

If not None, device specifies the corresponding device instance for device-dependent conversion.

class pylablib.core.devio.interface.ICheckingParameterClass(name)[source]

Bases: pylablib.core.devio.interface.IParameterClass

Parameter class which separately handles checking and conversion.

Specifies six methods: check_value(), to_alias() and _value_error_str for handling value-to-alias conversion, and check_alias(), to_value() and _alias_error_str for handling alias-to-value conversion.

check_alias(alias)[source]

Check if the alias is valid

check_value(value)[source]

Check if the device value is valid

to_value(alias)[source]

Convert the alias into a device value

to_alias(value)[source]

Convert the device value into an alias

i(value, device=None)[source]

Convert device parameter value into a corresponding use parameter value

If not None, device specifies the corresponding device instance for device-dependent conversion.

docstring()

Get a parameter docstring

using_device(device)

Context manager for temporarily changing the device attribute to the given device instance

class pylablib.core.devio.interface.RangeParameterClass(name, minval=None, maxval=None, out_of_range='error')[source]

Bases: pylablib.core.devio.interface.ICheckingParameterClass

Parameter class for numerical values constrained to a certain range.

Parameters:
  • name – parameter class name
  • minval – minimal allowed value (inclusive); None means no lower limit
  • maxval – maximal allowed value (inclusive); None means no upper limit
  • out_of_range – action if an out-of-range value is supplied; can be either "error" (raise an error), or "truncate" (truncate to the nearest limit).
check_value(value)[source]

Check if the device value is valid

check_alias(alias)[source]

Check if the alias is valid

to_value(alias)[source]

Convert the alias into a device value

docstring()[source]

Get a parameter docstring

i(value, device=None)

Convert device parameter value into a corresponding use parameter value

If not None, device specifies the corresponding device instance for device-dependent conversion.

to_alias(value)

Convert the device value into an alias

using_device(device)

Context manager for temporarily changing the device attribute to the given device instance

class pylablib.core.devio.interface.IEnumParameterClass(name, allowed_alias='device_values', allowed_value='exact', alias_case=None, value_case=None, match_prefix=False)[source]

Bases: pylablib.core.devio.interface.ICheckingParameterClass

Parameter class for a generic enum (i.e., predefined values) parameter.

Defines two methods for handling conversion:
  • _get_value_map which returns a dictionary for converting device values into aliases,
  • _get_alias_map which returns a dictionary for converting aliases into device values.

These methods need to be redefined in subclasses.

Parameters:
  • name – parameter class name
  • allowed_alias – specifies a range of allowed aliases; can be "exact" (only exact map matches are allowed), "device_value" (exact map matches and raw device values are allowed), or "all" (all values are allowed); in the latter two cases the value not in the map are passed as is.
  • allowed_value – specifies a range of allowed device values; can be "exact" (only exact map matches are allowed), or "all" (all values are allowed); in the latter case the value not in the map is passed as is.
  • alias_case – default alias parameter case for string values; can be None (no case normalization), or "lower" or "upper" (any received or returned alias will be normalized into this case)
  • value_case – default value parameter case for string values; can be None (no case normalization), or "lower" or "upper" (any received or returned device value will be normalized into this case)
  • match_prefix – if True, then the keys in the value map (returned by _get_value_map method) are interpreted as prefixes, so in the value-to-alias conversion the converted value matches the map value if it just starts with it; in the case of ambiguity (several map values are prefixes for the same converted value), the exact match takes priority; useful for some SCPI devices, where the shorter version of the value can sometimes be returned.
check_value(value)[source]

Check if the device value is valid

check_alias(alias)[source]

Check if the alias is valid

to_value(alias)[source]

Convert the alias into a device value

to_alias(value)[source]

Convert the device value into an alias

docstring()

Get a parameter docstring

i(value, device=None)

Convert device parameter value into a corresponding use parameter value

If not None, device specifies the corresponding device instance for device-dependent conversion.

using_device(device)

Context manager for temporarily changing the device attribute to the given device instance

class pylablib.core.devio.interface.EnumParameterClass(name, alias_map, value_map=None, allowed_alias='device_values', allowed_value='exact', alias_case=None, value_case=None, match_prefix=False)[source]

Bases: pylablib.core.devio.interface.IEnumParameterClass

Parameter class for a enum (i.e., predefined values) parameter with the specified mapping.

Parameters:
  • name – parameter class name
  • alias_map – mapping of aliases to device values; can be a dictionary, or a list of (alias,value) tuples (in the latter case non-tuple values are also allowed, indicating that value is the same as the alias); the list representation is useful in cases where the same alias maps to more than one value, so the map inversion is impossible
  • value_map – mapping of device values to aliases; can only be a dictionary or None, which means that the alias map is automatically inverted
  • allowed_alias – specifies a range of allowed aliases; can be "exact" (only exact map matches are allowed), "device_value" (exact map matches and raw device values are allowed), or "all" (all values are allowed); in the latter two cases the value not in the map are passed as is.
  • allowed_value – specifies a range of allowed device values; can be "exact" (only exact map matches are allowed), or "all" (all values are allowed); in the latter case the value not in the map is passed as is.
  • alias_case – default alias parameter case for string values; can be None (no case normalization), or "lower" or "upper" (any received or returned alias will be normalized into this case)
  • value_case – default value parameter case for string values; can be None (no case normalization), or "lower" or "upper" (any received or returned device value will be normalized into this case)
  • match_prefix – if True, then the keys in the value map (or values in the alias map, if only it is provided) are assumed to br prefixes, so in the value-to-alias conversion the converted value matches the map value if it just starts with it; useful for some SCPI devices, where the shorter version of the value can sometimes be returned.
check_alias(alias)

Check if the alias is valid

check_value(value)

Check if the device value is valid

docstring()

Get a parameter docstring

i(value, device=None)

Convert device parameter value into a corresponding use parameter value

If not None, device specifies the corresponding device instance for device-dependent conversion.

to_alias(value)

Convert the device value into an alias

to_value(alias)

Convert the alias into a device value

using_device(device)

Context manager for temporarily changing the device attribute to the given device instance

class pylablib.core.devio.interface.FunctionParameterClass(name, to_alias=None, to_value=None, check_value=None, check_alias=None, alias_err=None, value_err=None)[source]

Bases: pylablib.core.devio.interface.ICheckingParameterClass

Parameter class which uses supplied methods for checking, conversion, and generating error messages.

The arguments correspond to the parameter methods with the same names. When not supplied, checking methods always return True, conversion methods leave value intact, and error string methods generate the default error messages.

check_value(value)[source]

Check if the device value is valid

check_alias(alias)[source]

Check if the alias is valid

to_alias(value)[source]

Convert the device value into an alias

to_value(alias)[source]

Convert the alias into a device value

docstring()

Get a parameter docstring

i(value, device=None)

Convert device parameter value into a corresponding use parameter value

If not None, device specifies the corresponding device instance for device-dependent conversion.

using_device(device)

Context manager for temporarily changing the device attribute to the given device instance

class pylablib.core.devio.interface.CombinedParameterClass(name, parameters)[source]

Bases: pylablib.core.devio.interface.IParameterClass

A multi-stage combined parameter class, which performs several conversion/check stages.

Parameters:
  • name – parameter class name
  • parameters – list of parameters classes which are combined; the order is from the ‘most alias’ to the ‘most device parameter’, i.e., when converting an alias to a device parameter, it is first passed to the first class, then the second, etc. (the reverse is done when converting device values into aliases)
docstring()

Get a parameter docstring

i(value, device=None)[source]

Convert device parameter value into a corresponding use parameter value

If not None, device specifies the corresponding device instance for device-dependent conversion.

using_device(device)

Context manager for temporarily changing the device attribute to the given device instance

class pylablib.core.devio.interface.TRawParameterValue(value)

Bases: tuple

count()

Return number of occurrences of value.

index()

Return first index of value.

Raises ValueError if the value is not present.

value
pylablib.core.devio.interface.pval(value)[source]

Mark that the value has already been treated by the parameter class

pylablib.core.devio.interface.use_parameters(*args, **kwargs)[source]

Wrapper to indicate that a device class method uses device parameter classes.

The corresponding parameters classes are automatically determined if the argument name matches the parameter class name. The parameters classes can also be defined explicitly using keywords arguments arg=parameter supplied to the wrapper, where arg is the argument, and parameter is either a parameter class instance, or a parameter class name (the more preferable way). In addition, an argument _returns can be used to define the parameter class for the return value; it can also be a list or a tuple of parameter classes, indicating that the returned value is also a list or a tuple.

Module contents