You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python串口脚本仅能运行一次,再次运行报PermissionError求助

串口二次运行权限错误排查

我的代码在IDLE中首次运行正常,但结束后再次执行会出现权限错误,想知道是代码、硬件还是驱动的问题?

代码

import serial
import time

ser = serial.Serial('COM20', 9600, timeout=1)
print('port open is ' + str(ser.is_open))
time.sleep(2)
print('going to close')
ser.close()
print('port open is ' + str(ser.is_open))
time.sleep(2)

首次运行结果

port open is True
going to close
port open is False

报错信息

....
....\Python310\lib\site-packages\serial\serialwin32.py", line 222, in _reconfigure_port
raise SerialException(
serial.serialutil.SerialException: Cannot configure port, something went wrong. Original message: PermissionError(13, 'A device attached to the system is not functioning.', None, 31)

环境与已尝试操作

  • 串口为CH340设备,驱动版本3.8.2023.2
  • 运行环境:Windows10,无数据收发
  • 已尝试:重启系统、重装驱动、改端口为COM4、调整延迟、代码末尾加ser.open()(首次运行就报错)
  • 禁用/启用COM20后脚本可再次运行,但再次执行仍报错

问题分析与解决建议

从现象来看,大概率是CH340驱动与Windows串口机制的兼容性问题,而非代码本身的问题,具体分析和解决办法如下:

  1. 排除代码问题:你的代码逻辑没问题,serial.Serial()初始化时自动打开串口,最后也调用了ser.close(),首次运行能正常输出port open is False说明代码层面的串口操作是有效的。

  2. CH340驱动的常见缺陷:CH340芯片的新版Windows驱动偶尔会出现串口资源释放不彻底的情况——系统层面显示串口已关闭,但驱动内部仍占用资源,导致二次打开时触发权限/设备异常。

  3. 可行的解决办法:

    • 更换旧版本驱动:新驱动可能引入兼容性问题,试试CH340的2020年左右的稳定版本(比如3.6.2019.12),很多用户反馈新版本驱动容易出这类串口残留问题。
    • 改用上下文管理器写法:确保串口被彻底释放,改写代码如下:
      import serial
      import time
      
      with serial.Serial('COM20', 9600, timeout=1) as ser:
          print('port open is ' + str(ser.is_open))
          time.sleep(2)
          print('going to close')
      print('port open is ' + str(ser.is_closed))
      time.sleep(2)
      
      上下文管理器会自动处理异常和资源释放,比手动close()更可靠。
    • 排查硬件问题:如果换驱动和代码写法都没用,试试把CH340设备插到其他USB口,排除USB口供电或接触不良的问题;也可以换个CH340模块测试,排除硬件本身故障。

内容的提问来源于stack exchange,提问作者Ton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 02:32:37