PySerial连接断开耗时过长求助(树莓派3环境)
PySerial 串口断开连接耗时过长问题排查
我遇到PySerial断开连接耗时超1秒的异常问题,串口连接建立、数据收发速度均正常,传输耗时和波特率匹配(225bits数据约耗时0.09375秒)。在树莓派3上编写了最小复现代码,现象为with代码块退出时(自动执行close操作)耗时超1秒;手动添加s.close()调用时,耗时会集中在该语句上,with块则立即退出。
复现代码
#!/usr/bin/env python3 import datetime import serial def send_and_receive(): response_line = None try: with serial.Serial('/dev/ttyUSB2', 2400, timeout=1, write_timeout=1) as s: print(datetime.datetime.now().time(), "Executing command via serialio...") s.flushInput() s.flushOutput() s.write(b'QVFWb\x99\r') response_line = s.read_until(b"\r") s.read_all() print(datetime.datetime.now().time(),"serial response was: %s", response_line) #s.close() print(datetime.datetime.now().time(), "closed") return response_line except Exception as e: print(f"Serial read error: {e}") for i in range(10): print(datetime.datetime.now().time(), '--------------------') send_and_receive()
运行输出(注意断开连接的耗时)
21:31:43.739869 -------------------- 21:31:43.744267 Executing command via serialio... 21:31:43.851322 serial response was: %s b'(VERFW:000SR.34\x16\xef\r' 21:31:44.983403 closed 21:31:44.983702 -------------------- 21:31:44.987723 Executing command via serialio... 21:31:45.094942 serial response was: %s b'(VERFW:000SR.34\x16\xef\r' 21:31:46.193361 closed 21:31:46.193688 -------------------- 21:31:46.197638 Executing command via serialio... 21:31:46.307374 serial response was: %s b'(VERFW:000SR.34\x16\xef\r'
排查方向与解决办法
- 禁用流控引脚操作:PySerial默认关闭串口时会重置DTR/RTS引脚,部分USB转串口芯片(如CH340、PL2303)对引脚状态变化的响应较慢,导致close阻塞。初始化串口时添加参数关闭流控:
serial.Serial('/dev/ttyUSB2', 2400, timeout=1, write_timeout=1, dsrdtr=False, rtscts=False) - 强制清空缓冲区:虽然调用了
read_all(),但底层可能仍有残留数据未处理,PySerial会在close时等待缓冲区清空。在close前手动清空缓冲区:s.flush() s.reset_input_buffer() s.reset_output_buffer() - 禁用USB设备自动挂起:树莓派USB串口驱动可能存在设备休眠前的等待延迟,检查并修改设备的自动挂起设置:
echo -1 | sudo tee /sys/bus/usb-serial/devices/ttyUSB2/power/autosuspend - 升级PySerial版本:旧版本PySerial的close逻辑可能存在冗余等待,升级到最新版本尝试解决:
pip install --upgrade pyserial
内容的提问来源于stack exchange,提问作者DarkZeros
相关产品推荐
相关产品推荐

