在 Python serial 模块中使用 read() 或 readline() 函数

read() 和 readline() 函数是 Python serial 模块的重要组成部分。serial 模块提供访问串行端口所需的所有功能和必要条件。

本质上,可以说 serial 模块为在 Linux、Windows、OSX 等上运行的 Python 提供后端。简单来说,这意味着 serial 自动选择它认为合适的后端。

当我们需要一次读取多个字符时,让我们从 read() 函数及其应用开始。serial 模块的 read() 函数用于一次读取一个字节的给定文本。它包含一个参数,表示我们希望函数读取的最大 bytes 数量。

以下程序使用 read() 函数一次读取多个字符。

#general code of the serial module
import serial
ser = serial.Serial()
ser.port = 'COM2'
ser.baudrate = 19200
ser.timeout=0
x = ser.read()  # This function will read one byte from the given variable.

同样,我们可以使用 readline() 函数。它的工作方式与 read() 函数非常相似,但它一次读取整行。

但是,需要定义超时以正确实现 readline() 函数。此外,readline() 函数仅在遇到行尾或 eol(即 \n 换行符)后才会停止读取一行,因此在使用此函数时必须将其应用于每一行。

以下代码使用 readline() 函数一次读取多个字符。

#general code of the serial module
import serial
ser = serial.Serial()
ser.port = 'COM2'
ser.baudrate = 19200
ser.timeout=0
line = ser.readline() #This function reads one line at a time.