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
python类comports()的实例源码
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
def connected_microbits():
"""
Based on code from https://github.com/ntoll/microrepl
Returns a list of connected micro:bit port addresses (format is system
dependent).
"""
ports = list_serial_ports()
platform = sys.platform
results = []
if platform.startswith("linux"):
for port in ports:
if "VID:PID=0D28:0204" in port[2].upper():
results.append(port[0])
elif platform.startswith("darwin"):
for port in ports:
if "VID:PID=0D28:0204" in port[2].upper():
results.append(port[0])
elif platform.startswith("win"):
for port in ports:
if "VID:PID=0D28:0204" in port[2].upper():
results.append(port[0])
return results
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
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
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
def get_open_params_defaults(cls):
"""
Returns a list of parameters defaults. These will be displayed in the UI.
:return: default args: the default arguments provided to the user in the UI
"""
cls.default_args = BaseProtocol.get_open_params_defaults()
logger.info("[PCOM] Available COM ports: {0}".format(list_ports.comports()))
filtered_comports = cls._filter_com_ports(list_ports.comports())
logger.info("[PCOM]: filtered_comports:")
logger.info(filtered_comports)
potential_serials = [port_list[0] for port_list in filtered_comports]
cls.default_args['port'] = potential_serials
return cls.default_args
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
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
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
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
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
def refresh(self):
l = list(list_ports.comports())
new_ports = [Port(p) for p in l]
old_ports = self.getPortList()
# Add new ports to list
for p in new_ports:
if p not in self.getPortList():
self.list_w.addItem(p)
# Remove disappeared ports from list
for i in range(self.list_w.count()):
if(self.list_w.item(i) is not None):
p = self.list_w.item(i)
if p not in new_ports:
p.close()
self.list_w.takeItem(i)
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
def find_tty(self):
for port in comports():
if re.search(r'PID=2458:0*1', port[2]):
return port[0]
return None
# Runs and recieves packet while condition exists
def get_serial_ports():
"""Returns a list of all serial ports found, e.g. 'COM1' in Windows"""
return sorted([port.device for port in list_ports.comports()])
def _dump_ports(logger):
for d in list_ports.comports():
_dump_port(logger, d)
def select_port(logger = None, dev_port = None, filters = None, must_unique = False):
if filters != None and dev_port == None:
not_unique = False
for d in list_ports.comports():
is_match = True
for k, v in filters.items():
if not hasattr(d, k):
continue
a = getattr(d, k)
if not a:
a = ''
if a.find(v) == -1:
is_match = False
if is_match:
if dev_port == None:
dev_port = d.device
if logger:
logger.info('choose device: ' + dev_port)
_dump_port(logger, d)
else:
if logger:
logger.warning('find more than one port')
not_unique = True
if not_unique:
if logger:
logger.info('current filter: {}, all ports:'.format(filters))
_dump_ports(logger)
if must_unique:
raise Exception('port is not unique')
if not dev_port:
if logger:
if filters:
logger.error('port not found, current filter: {}, all ports:'.format(filters))
else:
logger.error('please specify dev_port or filters, all ports:')
_dump_ports(logger)
return None
return dev_port
def _get_serial_ports(self):
ports = [""]
for port, desc, hwid in sorted(list_ports.comports()):
ports.append(port)
return ports
def serial_port_info():
"""
:return: a tuple of serial port info tuples (port, name, desc)
"""
for p in list_ports.comports():
dev = (p.device, p.name, p.vid, p.pid)
yield dev
def dump_port_list():
if comports:
sys.stderr.write('\n--- Available ports:\n')
for port, desc, hwid in sorted(comports()):
#~ sys.stderr.write('--- %-20s %s [%s]\n' % (port, desc, hwid))
sys.stderr.write('--- %-20s %s\n' % (port, desc))
def get_port(self):
ports = []
for port in list_ports.comports():
if 'MCP2200' in port[1] or 'USB Serial Device' in port[1]:
ports.append(port[0])
if ports:
return ports[0]
else:
return None
def get_serial_ports():
"""Returns a list of all serial ports found, e.g. 'COM1' in Windows"""
# Grid simulator
# return ['/dev/pts/4']
return sorted([port.device for port in list_ports.comports()])
def find_microbit():
"""
Returns the port for the first micro:bit found connected to the computer.
"""
for port in comports():
if port.vid == MICROBIT_VID and port.pid == MICROBIT_PID:
return port.device
def dump_port_list():
if comports:
sys.stderr.write('\n--- Available ports:\n')
for port, desc, hwid in sorted(comports()):
#~ sys.stderr.write('--- %-20s %s [%s]\n' % (port, desc, hwid))
sys.stderr.write('--- %-20s %s\n' % (port, desc))
def dump_port_list():
if comports:
sys.stderr.write('\n--- Available ports:\n')
for port, desc, hwid in sorted(comports()):
#~ sys.stderr.write('--- %-20s %s [%s]\n' % (port, desc, hwid))
sys.stderr.write('--- %-20s %s\n' % (port, desc))
def dump_port_list():
if comports:
sys.stderr.write('\n--- Available ports:\n')
for port, desc, hwid in sorted(comports()):
#~ sys.stderr.write('--- %-20s %s [%s]\n' % (port, desc, hwid))
sys.stderr.write('--- %-20s %s\n' % (port, desc))
def get_open_params_defaults(cls):
"""Override base class function to show dropdowns for defaults"""
from serial.tools import list_ports
defaults = BaseProtocol.get_open_params_defaults()
potential_serials = [x[0] for x in list_ports.comports()]
defaults['port'] = potential_serials
defaults['baudrate'] = [300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200, 230400]
defaults['delimiter'] = "\n"
defaults['bytesize'] = 8
defaults['parity'] = "N"
defaults['stopbits'] = 1
return defaults
def _filter_com_ports(potential_com_ports):
"""
Filters the provided list of COM ports based on the string descriptor provided by the USB connection.
If the string descriptor matches those provided generally by ST Micro the port will be added to the filtered
list. If no new filtered ports are found the old list is returned.
:param potential_com_ports: list of potential COM ports found using list_ports.comports() (from serial.tools)
:return:
"""
def _is_valid_port(port_name):
return PCOMSerial.STM_VCP_STRING in port_name[1] or PCOMSerial.USB_SERIAL_CONV_STRING in port_name[1] or \
PCOMSerial.FTDI_VENDOR_ID in port_name[2] or (PCOMSerial.ST_VENDOR_ID in port_name[2] and
PCOMSerial.STLINK_STRING not in port_name[1]) or \
PCOMSerial.ST_VENDOR_ID in port_name[2] and PCOMSerial.ST_SNR in port_name[2]
result_list = []
try:
for port in potential_com_ports:
logger.info("PORT:")
logger.info(port)
if _is_valid_port(port):
result_list.append(port)
except Exception as e:
logger.error("[PCOM] Could not filter ports because of exception: {0}".format(e))
return potential_com_ports
return result_list if result_list else potential_com_ports
def list_ports(cls):
ports = comports()
for port in ports:
if port[1].startswith('EiBotBoard'):
yield port[0]
elif port[2].upper().startswith('USB VID:PID=04D8:FD92'):
yield port[0]