本文整理汇总了Python中serial.tools.list_ports.comports方法的典型用法代码示例。如果您正苦于以下问题:Python list_ports.comports方法的具体用法?Python list_ports.comports怎么用?Python list_ports.comports使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类serial.tools.list_ports
的用法示例。
在下文中一共展示了list_ports.comports方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: listEBBports
# 需要导入模块: from serial.tools import list_ports [as 别名]
# 或者: from serial.tools.list_ports import comports [as 别名]
def listEBBports():
# Find and return a list of all EiBotBoard units
# connected via USB port.
try:
from serial.tools.list_ports import comports
except ImportError:
return None
if comports:
com_ports_list = list(comports())
ebb_ports_list = []
for port in com_ports_list:
port_has_ebb = False
if port[1].startswith("EiBotBoard"):
port_has_ebb = True
elif port[2].startswith("USB VID:PID=04D8:FD92"):
port_has_ebb = True
if port_has_ebb:
ebb_ports_list.append(port)
if ebb_ports_list:
return ebb_ports_list
示例2: ask_for_port
# 需要导入模块: from serial.tools import list_ports [as 别名]
# 或者: from serial.tools.list_ports import comports [as 别名]
def ask_for_port():
"""\
Show a list of ports and ask the user for a choice. To make selection
easier on systems with long device names, also allow the input of an
index.
"""
sys.stderr.write('\n--- Available ports:\n')
ports = []
for n, (port, desc, hwid) in enumerate(sorted(comports()), 1):
sys.stderr.write('--- {:2}: {:20} {}\n'.format(n, port, desc))
ports.append(port)
while True:
port = raw_input('--- Enter port index or full name: ')
try:
index = int(port) - 1
if not 0 <= index < len(ports):
sys.stderr.write('--- Invalid index!\n')
continue
except ValueError:
pass
else:
port = ports[index]
return port
示例3: findPort
# 需要导入模块: from serial.tools import list_ports [as 别名]
# 或者: from serial.tools.list_ports import comports [as 别名]
def findPort():
# Find first available EiBotBoard by searching USB ports.
# Return serial port object.
try:
from serial.tools.list_ports import comports
except ImportError:
return None
if comports:
com_ports_list = list(comports())
ebb_port = None
for port in com_ports_list:
if port[1].startswith("EiBotBoard"):
ebb_port = port[0] # Success; EBB found by name match.
break # stop searching-- we are done.
if ebb_port is None:
for port in com_ports_list:
if port[2].startswith("USB VID:PID=04D8:FD92"):
ebb_port = port[0] # Success; EBB found by VID/PID match.
break # stop searching-- we are done.
return ebb_port
示例4: _find_port
# 需要导入模块: from serial.tools import list_ports [as 别名]
# 或者: from serial.tools.list_ports import comports [as 别名]
def _find_port(self):
from serial.tools import list_ports
import serial
import os
all_port_tuples = list_ports.comports()
logging.info("listing serial ports")
all_ports = set()
for ap, _, _ in all_port_tuples:
p = os.path.basename(ap)
print(p)
if p.startswith("ttyUSB") or p.startswith("ttyACM"):
all_ports |= {ap}
logging.info("\t%s", str(ap))
if len(all_ports) == 0:
logging.error("No valid port detected!. Possibly, device not plugged/detected.")
raise NoValidPortError()
elif len(all_ports) > 2:
logging.info("Several port detected, using first one: %s", str(all_ports))
return all_ports.pop()
示例5: ask_for_port
# 需要导入模块: from serial.tools import list_ports [as 别名]
# 或者: from serial.tools.list_ports import comports [as 别名]
def ask_for_port():
"""\
Show a list of ports and ask the user for a choice. To make selection
easier on systems with long device names, also allow the input of an
index.
"""
sys.stderr.write('\n--- Available ports:\n')
ports = []
for n, (port, desc, hwid) in enumerate(sorted(comports()), 1):
#~ sys.stderr.write('--- %-20s %s [%s]\n' % (port, desc, hwid))
sys.stderr.write('--- {:2}: {:20} {}\n'.format(n, port, desc))
ports.append(port)
while True:
port = raw_input('--- Enter port index or full name: ')
try:
index = int(port) - 1
if not 0 <= index < len(ports):
sys.stderr.write('--- Invalid index!\n')
continue
except ValueError:
pass
else:
port = ports[index]
return port
示例6: _find_port
# 需要导入模块: from serial.tools import list_ports [as 别名]
# 或者: from serial.tools.list_ports import comports [as 别名]
def _find_port(self):
all_port_tuples = list_ports.comports()
logging.info("listing serial ports")
all_ports = set()
for ap, _, _ in all_port_tuples:
all_ports |= {ap}
logging.info("\t%s", str(ap))
for ap in list(all_ports):
logging.info("trying port %s", str(ap))
try:
#here we use a recursive strategy to find the good port (ap).
SimpleLynxMotionConnection(ap)
return ap
except (WrongSleepDepPortError, serial.SerialException):
warn_str = "Tried to use port %s. Failed." % ap
logging.warning(warn_str)
pass
logging.error("No valid port detected!. Possibly, device not plugged/detected.")
raise NoValidPortError()
示例7: default_port
# 需要导入模块: from serial.tools import list_ports [as 别名]
# 或者: from serial.tools.list_ports import comports [as 别名]
def default_port(sysname=system(), detect=True):
"""This returns the default port used for different systems if SERIALPORT env variable is not set"""
system_default = {
'Windows': 'COM1',
'Darwin': '/dev/tty.SLAB_USBtoUART'
}.get(sysname, '/dev/ttyUSB0')
# if SERIALPORT is set then don't even waste time detecting ports
if 'SERIALPORT' not in environ and detect:
try:
ports = list_ports.comports(include_links=False)
if len(ports) == 1:
return ports[0].device
else:
# clever guessing, sort of
# vid/pid
# 4292/60000 adafruit huzzah
for p in ports:
if p.vid == 4292 and p.pid == 60000:
return p.device
# use last port as fallback
return ports[-1].device
except Exception:
pass
return environ.get('SERIALPORT', system_default)
示例8: extcap_interfaces
# 需要导入模块: from serial.tools import list_ports [as 别名]
# 或者: from serial.tools.list_ports import comports [as 别名]
def extcap_interfaces():
"""List available interfaces to capture from"""
log_file = open(
os.path.join(tempfile.gettempdir(), 'extcap_ot_interfaces.log'), 'w')
print(
'extcap {version=1.0.0}{display=OpenThread Sniffer}{help=https://github.com/openthread/pyspinel}'
)
threads = []
for interface in comports():
th = threading.Thread(target=serialopen, args=(interface, log_file))
threads.append(th)
th.start()
for th in threads:
th.join()
示例9: __init__
# 需要导入模块: from serial.tools import list_ports [as 别名]
# 或者: from serial.tools.list_ports import comports [as 别名]
def __init__(self, interface=None, baudrate=115200):
self.lock = Lock()
# Pick the first serial port that matches a Micro:Bit
# if no interface is provided
if interface is None:
for port in comports():
if type(port) is tuple:
if "VID:PID=0d28:0204" in port[-1]:
interface = port[0]
break
elif port.vid == 0x0D28 and port.pid == 0x0204:
interface = port.device
break
# If no interface found, we cannot do anything as we need at least
# one Micro:bit device connected.
if interface is None:
raise DeviceError('No Micro:Bit connected')
# If an interface was found, continue
self.interface = Serial(interface, baudrate, timeout=0)
self.rx_buffer = bytes()
示例10: format_filename
# 需要导入模块: from serial.tools import list_ports [as 别名]
# 或者: from serial.tools.list_ports import comports [as 别名]
def format_filename(s):
"""Take a string and return a valid filename constructed from the string.
Uses a whitelist approach: any characters not present in valid_chars are
removed. Also spaces are replaced with underscores."""
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
filename = ''.join(c for c in s if c in valid_chars)
filename = filename.replace(' ','_') # I don't like spaces in filenames.
return filename
# def vid_pid_to_serial_url(vidpid):
# #Get all com ports currently connected to the system
# currentComPorts = list(list_ports.comports())
# for port in currentComPorts:
# if re.search(vidpid, port[2], flags=re.IGNORECASE):
# return port[0]
# raise LookupError('VID:PID Not found on system')
示例11: devices
# 需要导入模块: from serial.tools import list_ports [as 别名]
# 或者: from serial.tools.list_ports import comports [as 别名]
def devices(self):
if sys.platform in ('win32', 'cygwin'):
return {pi.device: pi.device for pi in slp.comports()}
elif sys.platform == 'darwin':
devdir = "/dev/"
pattern = "^cu.usbserial-(.*)"
else:
devdir = "/dev/serial/by-id/"
pattern = "^usb-FTDI_FT230X_Basic_UART_(........)-"
if not os.access(devdir, os.R_OK):
return {}
devs = os.listdir(devdir)
def filter(d):
m = re.match(pattern, d)
if m:
return (m.group(1), devdir + d)
seldev = [filter(d) for d in devs]
return dict([d for d in seldev if d])
示例12: get_ports
# 需要导入模块: from serial.tools import list_ports [as 别名]
# 或者: from serial.tools.list_ports import comports [as 别名]
def get_ports(is_dump=True):
ports = []
for i in list_ports.comports():
# if i.pid is not None and '{:04x}:{:04x}'.format(i.vid, i.pid) == vidpid:
if i.pid is not None:
if is_dump:
_dump_port(i)
ports.append({
'pid': '{:04x}'.format(i.pid),
'vid': '{:04x}'.format(i.vid),
'device': i.device,
'serial_number': i.serial_number,
'hwid': i.hwid,
'name': i.name,
'description': i.description,
'interface': i.interface,
'location': i.location,
'manufacturer': i.manufacturer,
'product': i.product
})
return ports
示例13: ask_for_port
# 需要导入模块: from serial.tools import list_ports [as 别名]
# 或者: from serial.tools.list_ports import comports [as 别名]
def ask_for_port():
"""\
Show a list of ports and ask the user for a choice. To make selection
easier on systems with long device names, also allow the input of an
index.
"""
sys.stderr.write('\n--- Available ports:\n')
ports = []
for n, (port, desc, hwid) in enumerate(sorted(comports()), 1):
sys.stderr.write('--- {:2}: {:20} {!r}\n'.format(n, port, desc))
ports.append(port)
while True:
port = raw_input('--- Enter port index or full name: ')
try:
index = int(port) - 1
if not 0 <= index < len(ports):
sys.stderr.write('--- Invalid index!\n')
continue
except ValueError:
pass
else:
port = ports[index]
return port
示例14: printComPorts
# 需要导入模块: from serial.tools import list_ports [as 别名]
# 或者: from serial.tools.list_ports import comports [as 别名]
def printComPorts():
logMessage('Available COM ports:')
for i, port in enumerate(list_ports.comports()):
logMessage('%d: %s' % (i+1, port.device))
logOk('Done')
示例15: get_serial_ports
# 需要导入模块: from serial.tools import list_ports [as 别名]
# 或者: from serial.tools.list_ports import comports [as 别名]
def get_serial_ports():
from serial.tools.list_ports import comports
result = []
for port, description, hwid in comports():
if not port:
continue
if 'VID:PID' in hwid:
result.append({
'port': port,
'description': description,
'hwid': hwid
})
return result