Free Serial Port After SerialException "Access Denied" to Reconnect

I have a simple Connect class that creates a serial connection when instantiating.

import serial
import serial.tools.list_ports_windows as list_ports

class Connect:
    def __init__(self):
        connect(self)

    def connect(self):
        self.ser = serial.Serial(port='COM1')

    def disconnect(self):
        self.ser.close()

    def __del__(self):
        self.disconnect()
        del self.ser

If I create an instance of this class and then destroy my instance so that neither the disconnect () nor del () method is executed , the port will still be bound. Therefore, if I try to connect again, I get the following exception:

SerialException: could not open port 'COM1': WindowsError(5, 'Access is denied.')

What should I do with my code to disable the serial port, so I can connect to it using a new instance of Connect?

+4

Source: https://habr.com/ru/post/1626270/


All Articles