我正在通过RS232电缆与SR830锁定放大器通信。在读取数据时,如以下代码所示:
import serial
def main():
ser = serial.Serial(
port='COM6',
baudrate=19200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
ser.timeout=1
ser.write("OUTP? 1 \r\n".encode()) #Asks the Lock-in for x-value
ser.write("++read\r\n".encode())
x=ser.readline()
print (x)
if __name__ == '__main__': main()我得到一个像b'-3.7486e-008\r'这样的字节字符串。但是,ser.readline()函数不会将\r识别为下线。因此,每次读取数据时,我都必须等待超时,这将是很麻烦的,因为我想尽可能快地获得很多点。数字的长度变化很大,所以我不能只使用ser.read(12)。我尝试过使用io.TextIOWrapper,但我不清楚如何实现它。这是我的尝试:
import serial
import io
def main():
ser = serial.Serial(
port='COM6',
baudrate=19200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
ser.timeout=1
sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser))
sio.write("OUTP? 1 \r\n") #Asks the Lock-in for x-value
sio.write("++read\r\n")
x=sio.readline()
print (x)
if __name__ == '__main__': main()它只打印一个空格。任何帮助都将不胜感激,谢谢。
编辑:以下是我在答案之后的工作代码,使用循环:
import serial
def main():
ser = serial.Serial(
port='COM6',
baudrate=19200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
ser.timeout=5
ser.write("OUTP? 1 \r\n".encode()) #Asks the Lock-in for x-value
ser.write("++read\r\n".encode())
buffer = ""
while True:
oneByte = ser.read(1)
if oneByte == b"\r": #method should returns bytes
print (buffer)
break
else:
buffer += oneByte.decode()
if __name__ == '__main__': main()发布于 2017-07-20 21:21:00
使用简单的循环进行读取怎么样?
def readData():
buffer = ""
while True:
oneByte = ser.read(1)
if oneByte == b"\r": #method should returns bytes
return buffer
else:
buffer += oneByte.decode("ascii")你可以查看Pyserial包中的serialutil.py文件,它们使用相同的方法实现read_until。
发布于 2019-10-11 02:39:11
请改用read_until():
ser.read_until(b'\r')
注意,不要忘记b。否则,即使它读取了'\r‘,函数也不会返回,直到到达端口上设置的超时。
发布于 2017-07-20 21:37:51
对于二进制文件,行终止符始终为b'\n';对于文本文件,open()的newline参数可用于选择可识别的行终止符。
当然,您不能在这里使用open。但是您可以使用io.TextIOWrapper将字节流转换为文本流:
ser_text = io.TextIOWrapper(ser, newline='\r')
ser_text.readline()https://stackoverflow.com/questions/45215838
复制相似问题