Python serial(pySerial)读取带有EOL的行,而不是

2024-04-20 10:46:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在通过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()函数不能将该EOL识别为一个EOL。所以每次读取数据都要等待超时,这会很麻烦,因为我想尽快拿到很多分数。数字的长度变化很大,所以我不能只使用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()

Tags: ioimportreadifmainportdefserial
3条回答

用简单循环来阅读怎么样?

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

来自the docs for ^{}

The line terminator is always b'\n' for binary files; for text files, the newline argument to open() can be used to select the line terminator(s) recognized.

当然,这里不能使用open。但您可以使用io.TextIOWrapper将字节流转换为文本流:

ser_text = io.TextIOWrapper(ser, newline='\r')
ser_text.readline()

改为使用read_until():

读到(b'\r')

请小心,不要忘记b。否则,即使它读取了'\r',在达到端口上设置的超时之前,函数也不会返回。

相关问题 更多 >