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

PyQt应用中串口关闭失效导致无法重新连接的问题求助

PyQt应用中串口关闭失效导致无法重新连接的问题求助

我在按钮点击事件里调用这个串口连接/断开的函数,现在遇到个棘手的问题:点击断开按钮的时候明明没有报错,但再次尝试连接串口时,会触发如下错误:

Cannot configure port, something went wrong. Original message: PermissionError(13, 'A device attached to the system is not functioning.', None, 31)

更离谱的是,就算我完全关掉应用程序,串口资源好像也没真正被释放——重新打开应用还是连不上对应的串口,必须手动拔插USB设备才能恢复正常。

以下是我的实现代码:

def On_Connect_Click(Gui):
  if(Gui.connect_btn.text() == "Disconnect"):
    Gui.connect_btn.setText("Connect")
    Gui.connect_btn.setStyleSheet("background-color: #FFD700; ")
    Gui.write_thread.stop()
    Gui.read_thread.stop()
    time.sleep(0.1)  # Small delay to ensure buffers are cleared
    Gui.ser.close()
    del Gui.ser  # Remove the serial object completely
  else: # (self.connect_bt.text() == "Connect")
    try:
        # Set up serial connection
        Gui.ser = serial.Serial(Gui.port_combo.currentText(),
                            Gui.baud_combo.currentText(),
                            timeout=1,
                            bytesize=serial.EIGHTBITS,
                            stopbits=serial.STOPBITS_ONE,
                            parity=serial.PARITY_NONE)
        Gui.ser.read_buffer_size = 4096
    except Exception as e :
        print("Failed")
        print(e)
        Gui.show_message("Connection failed. Check the Port number.", title="Connection Failed")
        return
    # write_thread includes Writing multiple Regs command and Read_req command
    Start_read_write_threads(Gui)

    Gui.connect_btn.setText("Disconnect")
    Gui.connect_btn.setStyleSheet("background-color: Red; color: white;")
    time.sleep(1)  #If you delete this, UI will be closed.

我怀疑是不是读写线程没有被彻底停止,导致串口的读写操作还在后台进行,进而占着串口资源没释放?有没有大佬能帮我排查下问题所在?

备注:内容来源于stack exchange,提问作者Sedna.Kianfarooghi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 17:24:36