Pyserial: FileNotFoundError: [Errno 2] No such file or directory: 'COM3'

Viewed 1423

First post here.

I am trying to use Python to read data from a Lakeshore Model 218 Temperature Sensor, which uses an RS-232 port.

My diagnostic code:

import time
import serial
from serial.serialposix import Serial

print('starting')
#print(dir(serial.Serial))

print(dir(serial))
print('')
print(dir(Serial))

ser = serial.Serial(
    port="COM3",
    baudrate=9600,
    parity=serial.PARITY_ODD,
    stopbits=serial.STOPBITS_TWO,
    bytesize=serial.SEVENBITS
)

ser.open()
ser.isOpen()

When I run the code, I get an error saying the computer can't find my port no matter what I list the port as.

Here's the specific error that appears below:

Traceback (most recent call last):
  File "/Users/X/Desktop/cryostat/.venv/lib/python3.9/site-packages/serial/serialposix.py", line 322, in open
    self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
FileNotFoundError: [Errno 2] No such file or directory: 'COM3'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/X/Desktop/cryostat/standardplot.py", line 13, in <module>
    ser = serial.Serial(
  File "/Users/X/Desktop/cryostat/.venv/lib/python3.9/site-packages/serial/serialutil.py", line 244, in __init__
    self.open()
  File "/Users/X/Desktop/cryostat/.venv/lib/python3.9/site-packages/serial/serialposix.py", line 325, in open
    raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
serial.serialutil.SerialException: [Errno 2] could not open port COM3: [Errno 2] No such file or directory: 'COM3'

How do I locate and connect to the port?

1 Answers

Possibly, your device is on another COMx port (not COM3 as your code suggests). You could either check for the right COM port in the Device Manger on Windows or you could use the following python code snippet to find the open COM ports:

import serial.tools.list_ports as ports

com_ports = list(ports.comports())  # create a list of com ['COM1','COM2']
for i in com_ports:
    print(i.device)  # returns 'COMx'
Related