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

Python串口PermissionError 13求助:重复运行报错需重插USB

串口权限错误排查与解决

报错信息

serial.serialutil.SerialException: Cannot configure port, something went wrong. Original message: PermissionError(13, '无法访问端口,权限不足。', None, 31)

问题场景

首次插入USB后运行代码无异常,重复运行时触发上述权限错误,每次运行需重新插拔USB,已安装CH340驱动。

现有代码

import serial
import time

ser = None  # Initialize ser

try:
    ser = serial.Serial(
        port="COM4",  # Update this to the serial port of your device
        baudrate=9600,  # Update this according to your device's settings
        timeout=1,
        stopbits=1,
    )

    # Check if the serial port is open
    if ser.isOpen():
        print("Serial port is open")
    else:
        print("Error opening serial port")
        exit()

    # Send a SCPI command to query the voltage
    ser.write(b"VOLT 7\n")

    # Give the device some time to respond
    time.sleep(1)

    # Read the response
    response = ser.readline().decode().strip()
    print(f"Voltage: {response}")

finally:
    if ser is not None:  # Check if ser is not None before attempting to close it
        ser.close()

排查与解决方法

  • 端口资源未完全释放:虽然代码用finally块关闭了端口,但操作系统可能存在延迟释放的情况。可以修改finally块,显式置空串口对象并添加短暂延迟:
    finally:
        if ser is not None:
            ser.close()
            ser = None  # 帮助垃圾回收器回收资源
            time.sleep(0.5)  # 给系统留足端口释放时间
    
  • 进程占用或权限不足:
    • 打开任务管理器,排查是否有其他程序(如串口调试工具)占用了COM4端口,关闭后重试
    • 打开设备管理器,找到对应COM端口→右键属性→安全,确保当前用户拥有「读取/写入」权限
  • 驱动兼容性问题:卸载现有CH340驱动,重新安装官方最新版本,避免老旧驱动导致的端口异常
  • 改用上下文管理器优化代码:使用with语句自动管理串口资源,比手动close()更可靠,代码块结束后会自动释放端口:
    import serial
    import time
    
    try:
        with serial.Serial(
            port="COM4",
            baudrate=9600,
            timeout=1,
            stopbits=1,
        ) as ser:
            print("Serial port is open")
            ser.write(b"VOLT 7\n")
            time.sleep(1)
            response = ser.readline().decode().strip()
            print(f"Voltage: {response}")
    except serial.SerialException as e:
        print(f"串口操作错误: {e}")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 05:25:22