我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用serial.tools.list_ports.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 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 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 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 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]
def _discover_devices(self): comport_lst = list_ports.comports() return {p.device: '{}, {}'. format(p.manufacturer, p.description) for p in comport_lst}
def find_all_serial_ports(): """ :return: a list of serial port info tuples :rtype: """ all_ports = list_ports.comports() return iter(all_ports)
def get_modems(): """Return a list of modems plugged into the computer. Switched to text mode. """ ports = list_ports.comports() ports = [s.device for s in ports if s.device.startswith(pre)] no1 = True if 'Modem' in ''.join(ports) else False ports = [int(p.replace(pre, '')) for p in ports if p[-1].isdigit()] ports = [(y, z) for x,y,z in seq(ports, 3)] if no1: ports.append(('Modem', 'Pcui')) modems, info = {}, [] for i, pair in enumerate(ports): try: modems[i] = humod.Modem( pre+str(pair[0]), pre+str(pair[1]) ) modems[i].enable_textmode(True) except SerialException as e: info.append(('Not connected.', str(e), i+1)) except OSError as e: info.append(('Power off.', str(e), i+1)) except humod.errors.AtCommandError as e: info.append(('', str(e), i+1)) del modems[i] return modems, info
def detect_tty(self): for p in comports(): if re.search(r'PID=2458:0*1', p[2]): print('using device:', p[0]) return p[0] return None
def find_serial_port(): """ tries to connect to all available serial ports, returns of first successful connection. exit if none works :return: serial interface object """ if settings.debug_port_detection: for port in list_ports.comports(): print('trying {}'.format(port[0])) return serial.Serial(settings.forced_port, settings.baud_rate, timeout=1) else: for port in (list_ports.comports()): print('trying {}'.format(port[0])) try: serial_interface = serial.Serial(port[0], settings.baud_rate, timeout=2) sleep(2) # wait for the device to be ready # send hello command serial_interface.write(settings.handshake_challenge) # check if this device knows what to reply reply = serial_interface.read(len(settings.handshake_response)) print(reply) if reply == settings.handshake_response: return serial_interface except serial.SerialException: # print("opening serial failed") pass raise ConnectionError("Couldn't connect to any serial ports, exiting...")
def get_available_ports(): ports = [] portlist = list_ports.comports() if item_count(portlist) == 0: return iterator = sorted(list(portlist)) for port, desc, hwid in iterator: ports.append((port, desc)) return ports
def search(self): #Return the 1st board founded with Exode installed logCore("Searching for a board...") boardList=[] # Search a port if platform.system() == 'Windows': ports = windows_ports() elif platform.system() == 'Darwin': ports = [i[0] for i in list_ports.comports()] else: ports = glob.glob("/dev/ttyUSB*") + glob.glob("/dev/ttyACM*") for p in ports: try: logCore("Try to connect to :"+p) sr = serial.Serial(p, 9600) except (serial.serialutil.SerialException, OSError) as e: continue time.sleep(2) # This bit array execute the function checkExode() # on the board sr.write(bytearray([2, 0, ID('checkExode')])) sr.flush() time.sleep(0.25) # the board should answer 202,404 ans= [0,0] if sr.inWaiting()>0: ans[0] = int.from_bytes(sr.read(), byteorder='little') ans[1] = int.from_bytes(sr.read(4), byteorder='little', signed=False) logCore(p+" answered "+str(ans)) if ans != [202,404]: continue else: logCore("Arduino board detected with Exode at : "+p) boardList.append(p) return boardList
def deviceQuery(self): try: devices = comports() for d in devices: if len(d.hwid.split('PID')) > 1: if d.hwid.split('PID')[1].split()[0][1:].lower() == self.device['identifier']: self.device['port'] = d.device return d.device except Exception: return None return None
def find_microbit(): """ Finds the port to which the device is connected. """ ports = list_serial_ports() for port in ports: if "VID:PID=0D28:0204" in port[2].upper(): return port[0] return None
def get_coms(self): close_fds = False if sys.platform == 'win32' else True if sys.platform == 'win32': cmd_subprc_pipe = subprocess.Popen("%s coms" % self._pjon_piper_path, shell=False, close_fds=close_fds, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=0, startupinfo=self._startupinfo, env=os.environ) else: cmd_subprc_pipe = subprocess.Popen([self._pjon_piper_path, "coms"], shell=False, close_fds=close_fds, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=0, env=os.environ) coms = [] #log.debug(">> cmd pipe out") while cmd_subprc_pipe: try: nex_tline = cmd_subprc_pipe.stdout.readline() if nex_tline == '': break #log.debug(nex_tline.strip()) if self.is_string_valid_com_port_name(nex_tline.strip()): #log.debug("\_got a com port in the stdout") coms.append(nex_tline.strip()) else: pass #log.error("suspicious COM name in the output: %s" % nex_tline.strip()) except AttributeError: pass #log.debug("<< cmd pipe out") cmd_subprc_pipe.terminate() if coms == []: log.warn("PJON-piper returned no serial ports; falling back to pyserial to enumerate available serials") from serial.tools import list_ports if sys.platform == 'win32': coms = [item.device for item in list_ports.comports()] elif sys.platform == 'linux2': coms = [item[0] for item in list_ports.comports()] return coms
def setupAvailablePorts(self): """ Purpose: Determine what ports are available for serial reading and populate the combo box with these options Input: None Output: None """ self.comboBox_serialPort.clear() listPortInfoObjects = list_ports.comports() portNames = [x[0] for x in listPortInfoObjects] self.comboBox_serialPort.addItems(portNames)
def serial_port(): def ok(): global ser, port port = var.get() port = port.split(' - ') bracket = '(\'' port_str_index = port[0].find(bracket) if port_str_index != -1: port[0] = (port[0])[port_str_index + 2:] ser = serial.Serial(port[0], 115200) win.destroy() global win win = Tk() win.wm_title('Choose a Serial Port') var = StringVar(win) var.set("Select the port your Arduino is connected to") ports = list(list_ports.comports()) option = OptionMenu(win, var, ports) option.pack(side='left') button = Button(win, text="OK", command=ok) button.pack() win.wm_protocol("WM_DELETE_WINDOW", window_exit) win.mainloop() # Wait for Arduino to respond
def available_hosts(cls): return list(p.device for p in comports() if p.manufacturer in white_list)
def get_port(self): ports = [] for port in list_ports.comports(): if 'MCP2200' in port[1] or 'USB Serial Device' in port[1] or 'USB Serial Port' in port[1]: ports.append(port[0]) if ports: return ports[0] else: return None
def list_serial_ports(): """Prints the open serial ports line per line""" warn("list_serial_ports now deprecated, use print_all_serial_ports instead", DeprecationWarning) ports = comports() for port in ports: print(port)
def print_all_serial_ports(): """Prints the open serial ports line per line""" ports = comports() for port in ports: print(port)
def get_serial_ports(): """Returns the open serial ports""" return comports()
def list_com_ports(self): """ Returns list of com ports found on the system. This is thin-wrapper of serial.tools.list_ports. Returned list consists of possible ListPortInfo instances. You may access attributes of ListPortInfo by extended variable syntax, e.g.:: @{ports} = List Com Ports Log ${ports[0].device} """ return comports()