Python Serial:如何使用 read 或 readline 函数一次读取多个字符

Python Serial: How to use the read or readline function to read more than 1 character at a time(Python Serial:如何使用 read 或 readline 函数一次读取多个字符)
本文介绍了Python Serial:如何使用 read 或 readline 函数一次读取多个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用我的程序读取多个字符,我似乎无法弄清楚我的程序出了什么问题.

I'm having trouble to read more than one character using my program, I can't seem to figure out what went wrong with my program.

import serial

ser = serial.Serial(
    port='COM5',
    baudrate=9600,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
        timeout=0)

print("connected to: " + ser.portstr)
count=1

while True:
    for line in ser.read():

        print(str(count) + str(': ') + chr(line) )
        count = count+1

ser.close()

这是我得到的结果

connected to: COM5
1: 1
2: 2
3: 4
4: 3
5: 1

其实我早就料到了

connected to: COM5
1:12431
2:12431

类似于上面提到的东西,它可以同时读取多个字符,而不是一个一个.

something like the above mentioned which is able read multiple characters at the same time not one by one.

推荐答案

我发现了几个问题.

第一:

ser.read() 一次只会返回 1 个字节.

ser.read() is only going to return 1 byte at a time.

如果您指定计数

ser.read(5)

它将读取 5 个字节(如果在 5 个字节到达之前发生超时,则更少.)

it will read 5 bytes (less if timeout occurrs before 5 bytes arrive.)

如果您知道您的输入始终以 EOL 字符正确终止,更好的方法是使用

If you know that your input is always properly terminated with EOL characters, better way is to use

ser.readline()

这将继续读取字符,直到收到 EOL.

That will continue to read characters until an EOL is received.

第二:

即使你让 ser.read() 或 ser.readline() 返回多个字节,由于您正在迭代返回值,因此您将仍然一次处理一个字节.

Even if you get ser.read() or ser.readline() to return multiple bytes, since you are iterating over the return value, you will still be handling it one byte at a time.

摆脱

for line in ser.read():

然后说:

line = ser.readline()

这篇关于Python Serial:如何使用 read 或 readline 函数一次读取多个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)