[Python] Python code to detect and verify which serial com port is open

Discussão em 'Python' iniciado por Stack, Março 5, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to write automated code in Python that will first list all available serial com ports on a PC (in Windows 10) and then checks which is active (open).

    import serial

    active_ports = [port.device for port in serial.tools.list_ports.comports()]
    print(active_ports)

    # and then put in a for loop to test each
    ser = serial.Serial(active_ports, 9600, timeout=1)


    But after last line it is just stuck there.

    But when I specify the port number I get this:

    import serial

    ser = serial.Serial("COM5", 9600, timeout=1)


    Traceback (most recent call last):
    File "<pyshell#7>", line 1, in <module>
    ser = serial.Serial("COM5", 9600, timeout=1)
    File "C:\Users\ghoura\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\serial\serialwin32.py", line 33, in __init__
    super(Serial, self).__init__(*args, **kwargs)
    File "C:\Users\ghoura\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\serial\serialutil.py", line 244, in __init__
    self.open()
    File "C:\Users\ghoura\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\serial\serialwin32.py", line 64, in open
    raise SerialException("could not open port {!r}: {!r}".format(self.portstr, ctypes.WinError()))
    serial.serialutil.SerialException: could not open port 'COM5': OSError(22, 'The semaphore timeout period has expired.', None, 121)

    Continue reading...

Compartilhe esta Página