串口通讯的python模块——pySerial

pySerial是一个用于Python的串口通信库,支持多种平台包括Windows、Linux等。它提供了统一的接口来配置和使用串口,并支持不同的波特率、数据位、停止位等设置。本文介绍如何安装pySerial并演示了基本的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pySerial

Overview

This module encapsulates the access for the serial port. It provides backends for Python running on Windows, Linux, BSD (possibly any POSIX compliant system), Jython and IronPython (.NET and Mono). The module named "serial" automatically selects the appropriate backend.

It is released under a free software license, see  LICENSE.txt for more details.
(C) 2001-2008 Chris Liechti  cliechti@gmx.net

The  project page on SourceForge and here is the  SVN repository and the  Download Page.
The homepage is on  http://pyserial.sf.net/

Features

  • same class based interface on all supported platforms
  • access to the port settings through Python 2.2+ properties
  • port numbering starts at zero, no need to know the port name in the user program
  • port string (device name) can be specified if access through numbering is inappropriate
  • support for different bytesizes, stopbits, parity and flow control with RTS/CTS and/or Xon/Xoff
  • working with or without receive timeout
  • file like API with "read" and "write" ("readline" etc. also supported)
  • The files in this package are 100% pure Python. They depend on non standard but common packages on Windows (pywin32) and Jython (JavaComm). POSIX (Linux, BSD) uses only modules from the standard Python distribution)
  • The port is set up for binary transmission. No NULL byte stripping, CR-LF translation etc. (which are many times enabled for POSIX.) This makes this module universally useful.

Requirements

  • Python 2.2 or newer
  • pywin32 extensions on Windows
  • "Java Communications" (JavaComm) or compatible extension for Java/Jython

Installation


from source

Extract files from the archive, open a shell/console in that directory and let Distutils do the rest:
python setup.py install

The files get installed in the "Lib/site-packages" directory.

easy_install

An EGG is available from the Python Package Index:  http://pypi.python.org/pypi/pyserial
easy_install pyserial

windows installer

There is also a Windows installer for end users. It is located in the  Download Page
Developers may be interested to get the source archive, because it contains examples and the readme.

Short introduction

Open port 0 at "9600,8,N,1", no timeout
>>> import serial
>>> ser = serial.Serial(0)  # open first serial port
>>> print ser.portstr       # check which port was really used
>>> ser.write("hello")      # write a string
>>> ser.close()             # close port
Open named port at "19200,8,N,1", 1s timeout
>>> ser = serial.Serial('/dev/ttyS1', 19200, timeout=1)
>>> x = ser.read()          # read one byte
>>> s = ser.read(10)        # read up to ten bytes (timeout)
>>> line = ser.readline()   # read a '\n' terminated line
>>> ser.close()
Open second port at "38400,8,E,1", non blocking HW handshaking
>>> ser = serial.Serial(1, 38400, timeout=0,
...                     parity=serial.PARITY_EVEN, rtscts=1)
>>> s = ser.read(100)       # read up to one hundred bytes
...                         # or as much is in the buffer
Get a Serial instance and configure/open it later
>>> ser = serial.Serial()
>>> ser.baudrate = 19200
>>> ser.port = 0
>>> ser
Serial<id=0xa81c10, open=False>(port='COM1', baudrate=19200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0)
>>> ser.open()
>>> ser.isOpen()
True
>>> ser.close()
>>> ser.isOpen()
False
Be carefully when using "readline". Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received. Also note that "readlines" only works with a timeout. "readlines" depends on having a timeout and interprets that as EOF (end of file). It raises an exception if the port is not opened correctly.
Do also have a look at the example files in the examples directory in the source distribution or online.

Examples

Please look in the SVN Repository. There is an example directory where you can find a simple terminal and more.
http://pyserial.svn.sourceforge.net/viewvc/pyserial/trunk/pyserial/examples/

Parameters for the Serial class

ser = serial.Serial(
port=None,              # number of device, numbering starts at
# zero. if everything fails, the user
# can specify a device string, note
# that this isn't portable anymore
# if no port is specified an unconfigured
# an closed serial port object is created
baudrate=9600,          # baud rate
bytesize=EIGHTBITS,     # number of databits
parity=PARITY_NONE,     # enable parity checking
stopbits=STOPBITS_ONE,  # number of stopbits
timeout=None,           # set a timeout value, None for waiting forever
xonxoff=0,              # enable software flow control
rtscts=0,               # enable RTS/CTS flow control
interCharTimeout=None   # Inter-character timeout, None to disable
)
The port is immediately opened on object creation, if a port is given. It is not opened if port is None.
Options for read timeout:
timeout=None            # wait forever
timeout=0               # non-blocking mode (return immediately on read)
timeout=x               # set timeout to x seconds (float allowed)

Methods of Serial instances

open()                  # open port
close()                 # close port immediately
setBaudrate(baudrate)   # change baud rate on an open port
inWaiting()             # return the number of chars in the receive buffer
read(size=1)            # read "size" characters
write(s)                # write the string s to the port
flushInput()            # flush input buffer, discarding all it's contents
flushOutput()           # flush output buffer, abort output
sendBreak()             # send break condition
setRTS(level=1)         # set RTS line to specified logic level
setDTR(level=1)         # set DTR line to specified logic level
getCTS()                # return the state of the CTS line
getDSR()                # return the state of the DSR line
getRI()                 # return the state of the RI line
getCD()                 # return the state of the CD line

Attributes of Serial instances

Read Only:
portstr                 # device name
BAUDRATES               # list of valid baudrates
BYTESIZES               # list of valid byte sizes
PARITIES                # list of valid parities
STOPBITS                # list of valid stop bit widths
New values can be assigned to the following attributes, the port will be reconfigured, even if it's opened at that time:

port                    # port name/number as set by the user
baudrate                # current baud rate setting
bytesize                # byte size in bits
parity                  # parity setting
stopbits                # stop bit with (1,2)
timeout                 # timeout setting
xonxoff                 # if Xon/Xoff flow control is enabled
rtscts                  # if hardware flow control is enabled

Exceptions

serial.SerialException

Constants

parity:
    serial.PARITY_NONE
serial.PARITY_EVEN
serial.PARITY_ODD
stopbits:
    serial.STOPBITS_ONE
serial.STOPBITS_TWO
bytesize:
    serial.FIVEBITS
serial.SIXBITS
serial.SEVENBITS
serial.EIGHTBITS

### 如何在 Python 中创建或配置虚拟串口 要实现在 Python 中创建或配置虚拟串口的功能,可以通过 `pyserial` 库中的子模块 `serial.tools.list_ports` 和其他第三方工具来模拟虚拟 COM 端口。以下是具体方法: #### 使用 PySerial 的基础 PySerial 是一个用于处理串行通信的强大库[^1]。它不仅支持物理串口设备的操作,还可以配合某些外部驱动程序(如 Virtual Serial Port Driver, VSPD)一起工作,从而实现虚拟串口的仿真。 #### 安装必要的依赖项 为了使用虚拟串口,在安装好 `pyserial` 之后还需要额外准备一些工具: - **Virtual Serial Port Driver (VSPD)**:这是 Windows 平台上常用的虚拟串口驱动程序,能够帮助创建一对或多对虚拟 COM 端口。 - **socat 工具**(适用于 Linux 或 macOS 用户):它可以用来建立本地套接字连接以模仿串口行为。 对于 Windows 用户来说,通常会先下载并安装 VSPD 来设置两个配对好的虚拟 COM 端口号,比如 `COM10` 和 `COM11`。一旦这些端口被成功创建出来以后就可以利用它们来进行读写测试了[^2]。 #### 示例代码展示 下面是一个简单的例子展示了如何通过 PySerial 对象打开已存在的虚拟串口并与之交互: ```python import serial def create_virtual_serial(): try: # 假设已经由 VSPD 创建了一组虚拟串口 COM10/COM11 ser = serial.Serial('COM10', baudrate=9600, timeout=1) if not ser.is_open: raise Exception("Failed to open the virtual serial port.") test_message = b"Hello, Virtual Serial Port!" bytes_written = ser.write(test_message) print(f"{bytes_written} byte(s) written successfully.") response = ser.read(len(test_message)) if response == test_message: print("Message echoed back correctly:", response.decode()) else: print("Unexpected reply received from the other end of the link.", response.decode()) except Exception as e: print(e) finally: if 'ser' in locals() and ser.is_open: ser.close() create_virtual_serial() ``` 此脚本尝试连接至指定名称为 `'COM10'` 的虚拟串口,并向其中发送一条消息 `"Hello, Virtual Serial Port!"` 。随后再次从同一通道里读取相同长度的数据流作为回应验证两者之间确实存在有效的双向通讯链路。 #### 注意事项 当涉及到实际应用开发时,请务必确认所使用的操作系统版本及其兼容性问题;另外还需注意安全权限方面的要求——尤其是在生产环境中部署解决方案之前应充分考虑潜在风险因素。 ---
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值