首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python串行(pySerial)使用EOL读取行\r而不是\n

Python串行(pySerial)使用EOL读取行\r而不是\n
EN

Stack Overflow用户
提问于 2017-07-20 21:13:26
回答 3查看 16.5K关注 0票数 1

我正在通过RS232电缆与SR830锁定放大器通信。在读取数据时,如以下代码所示:

代码语言:javascript
复制
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,但我不清楚如何实现它。这是我的尝试:

代码语言:javascript
复制
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()

它只打印一个空格。任何帮助都将不胜感激,谢谢。

编辑:以下是我在答案之后的工作代码,使用循环:

代码语言:javascript
复制
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()
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-07-20 21:21:00

使用简单的循环进行读取怎么样?

代码语言:javascript
复制
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

票数 5
EN

Stack Overflow用户

发布于 2019-10-11 02:39:11

请改用read_until():

ser.read_until(b'\r')

注意,不要忘记b。否则,即使它读取了'\r‘,函数也不会返回,直到到达端口上设置的超时。

票数 2
EN

Stack Overflow用户

发布于 2017-07-20 21:37:51

来自the docs for readline()

对于二进制文件,行终止符始终为b'\n';对于文本文件,open()newline参数可用于选择可识别的行终止符。

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

代码语言:javascript
复制
ser_text = io.TextIOWrapper(ser, newline='\r')
ser_text.readline()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45215838

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档