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

程序崩溃/被强制结束后PySerial出现PermissionError问题求助

串口权限问题:程序崩溃/强制结束后无法重新打开COM口

首次运行程序时能正常打开串口,但当用户通过任务管理器强制结束程序或程序崩溃后,再次运行程序会报错:

could not open port 'COM3': PermissionError(13, 'Access is denied.', None, 5)

我的代码如下:

def connect(self):
    try:
        self.ser = serial.Serial(port=self.ser_config.com_port,baudrate=self.ser_config.baud_rate, parity=self.ser_config.parity,xonxoff=self.ser_config.xonxoff, timeout=self.ser_config.timeout)
        if self.ser.is_open:
            print("Serial port " + self.ser_config.com_port + " opened!")
            print("Serial Configuration: baud_rate=" + str(self.ser_config.baud_rate))
            return True
        else:
            if self.ser:
                self.ser.close()
            print("Could not open serial port.")
            return False
    except serial.SerialException as se:
        if self.ser:
            self.ser.close()
        print("Serial port " + self.ser_config.com_port + " not found or cannot be configured")
        print(se)
        return False

推测这是因为首次运行时程序获取了串口的独占权限,再次运行时无法访问。且报错时self.ser为None,无法执行self.ser.close()。

请问有没有办法强制关闭该串口,或通过其他方式打开串口,避免用户重启电脑或手动关闭串口?


内容的提问来源于stack exchange,提问作者James C.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 14:27:39