我正在尝试找到设备所连接的正确com端口,然后才能运行其余的Python脚本。
我尝试过使用它:
import serial.tools.list_ports
ports = list(serial.tools.list_ports.comports())
for p in ports:
print p
而且:
import wmi
c = wmi.WMI()
wql = "Select * From Win32_SerialPort"
for item in c.query(wql):
print item
而且:
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
所有这些方法都是我从其他堆栈交换帖子中找到的方法;但是,对于这两个功能,当我尝试打印COM端口列表时,我得到一个空白列表?任何帮助/见解将非常感谢提前感谢!
答案 0 :(得分:0)
像这样:
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()
永远不能在没有速度(时钟)定义的情况下打开任何serial
端口。
在linux上:run as root
,普通用户无法访问/dev
(请勿更改动态创建权限cos name_space。不好主意!)。