As I understand, you have several devices on com
ports and you would like to select one of them and assign that port to VARIABLE
.
Below is a code that reads COM
port and assigns first port as usable COM port. It then probes the COM
port to see if its open.
You can inspect serial_ports()
output to determine which COM PORT
you want to use and assign the respective port slice
accordingly to VARIABLE
. I've used port 0
which is my COM1
The function serial_ports()
is cross platform. I have windows and it works seamlessly.
Inspiration from here
Demo Code
import sys
import glob
import serial
def serial_ports():
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(256)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
# this excludes your current terminal "/dev/tty"
ports = glob.glob('/dev/tty[A-Za-z]*')
elif sys.platform.startswith('darwin'):
ports = glob.glob('/dev/tty.*')
else:
raise EnvironmentError('Unsupported platform')
result = []
for port in ports:
try:
s = serial.Serial(port)
s.close()
result.append(port)
except (OSError, serial.SerialException):
pass
return result
if __name__ == '__main__':
VARIABLE = serial_ports()[0] #Assign first port as COM port
ser = serial.Serial(
port=VARIABLE,
baudrate=115200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
print "Is port", VARIABLE , " open ?", ser.isOpen()
Output
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>>
Is port COM1 open ? True
>>>