Reputation: 37
I am trying to find the correct com port a device is connected to before being able to run the rest of the Python script.
I have tried using this:
import serial.tools.list_ports
ports = list(serial.tools.list_ports.comports())
for p in ports:
print p
And this:
import wmi
c = wmi.WMI()
wql = "Select * From Win32_SerialPort"
for item in c.query(wql):
print item
And this:
def serial_ports():
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(256)]
print ports
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
All of these methods are ones that I have found from other stack exchange posts; however, with both functions, when I try to print the list of com ports I get a blank list? Any help/insights would be greatly appreciated thanks in advance!
Upvotes: 2
Views: 1030
Reputation: 1510
Like this :
import serial,os,sys,glob
def serial_ports():
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(256)]
print ports
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 = []
print ports
for port in ports:
try:
s = serial.Serial(port,9600)
s.close()
result.append(port)
except (OSError, serial.SerialException):
pass
return result
print serial_ports()
Never can open any serial
port without speed (clock) definition.
On linux : run as root
, normal user can't access /dev
(Don't change permission cos name_space creating dynamically. Bad idea !).
Upvotes: 1