Search code examples
pythonwindowsserial-portwindows-subsystem-for-linux

How to read data from a serial port in Windows using python?


In windows 10 I am trying to read the output of an attached serial device.

Using hterm I am able to see the data on serial port COM5. So the serial port works fine.

Now using WSL2 (Ubuntu 20.04.3) I am running the following python script

import serial

ser = serial.Serial("COM5", baudrate=115200)

which fails with the error

Traceback (most recent call last):
  File "test1.py", line 6, in <module>
    ser = serial.Serial("COM5", baudrate=115200)
  File "/usr/lib/python3/dist-packages/serial/serialutil.py", line 240, in __init__
    self.open()
  File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 268, in open
    raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
serial.serialutil.SerialException: [Errno 2] could not open port COM5: [Errno 2] No such file or directory: 'COM5'

I also tried to use the suggestions posted in this article at attach the USB port on which the serial device is connected to, to WSL.

The command usbipd wsl list in a windows powershell shows then

8-3    0403:6001  USB Serial Converter                                          Attached - Ubuntu-20.04

But when then running the same python code in WSL2 gives the same error.

So how to fix this problem so I am able to just read all data from the serial port with python?


Solution

  • You could try using the following script.

    import serial
    
    ser = serial.Serial("COM5", baudrate=115200, timeout=1)`
    while True:
       data = ser.readline()
       print(data)