我在测量仪器上遇到了同样的问题,花了一段时间才找到解决方案:
device.bytes_in_buffer
为您提供缓冲区内的字节数和
answer = device.read_bytes( device.bytes_in_buffer )
返回缓冲区内的字节。
之后,您可以调用answer.decode()
以获取设备返回给您的 ASCII 字符串。下面是一个较长的 Python 类示例,我为使与设备的通信更容易而编写:
import pyvisa as visa
import logging as log
import time
from typing import Final, Union
class interface: # provide write(), read(), read_raw(), ask() and ask_raw() function
_device = None
def __init__(self, device) -> None:
self._device = device
def write(self, command) -> None:
self._device.write("%s" % ( command))
def read(self) -> str:
return self.read_raw().decode()
def read_raw(self) -> str:
return self._device.read_bytes( self._device.bytes_in_buffer )
def ask(self, command) -> str:
return self.ask_raw(command).decode()
# flush buffer, this is necessary to prevent from errors because the last SCPI command took to long to be received
def flush_buffer(self) -> None:
self._device.flush(visa.constants.VI_READ_BUF)
def ask_raw(self, command) -> str:
self.flush_buffer()
self.write(command)
time.sleep(0.2) # this is needed for the device to process the SCPI command
return self.read_raw()
def boolean_property(
self,
scpi_cmd: str, # command name of scpi option
err_description: str, # generate usefull error messages
value: Union[bool, None] = None # True or False -> set scpi option to value, None -> get current value of scpi option
) -> Union[bool, None]:
# if parameter value is None -> get current state from scpi option
if value == None:
return {
"ON": True,
"1": True,
"OFF": False,
"0": False
}[str(
self.ask("%s?" % (scpi_cmd.upper()))
).upper()] # uppercase conversion is used to prevent issues with unexpected lowercase letters
# check wether the parameter is a boolean
if not type(value) == bool:
return log.error("%s: Cannot assign \"%s\" for %s, must be bool(True) or bool(False)" % (self._device, value, err_description))
# write the scpi command
self.write("%s %s" % (
scpi_cmd,
{
True: "ON",
False: "OFF"
}[value]
))