Python serial.tools.list_ports.comports() Examples

The following are 30 code examples for showing how to use serial.tools.list_ports.comports(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module serial.tools.list_ports , or try the search function .

Example 1
Project: plotink   Author: evil-mad   File: ebb_serial.py    License: MIT License 10 votes vote down vote up
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 
Example 2
Project: ethoscope   Author: gilestrolab   File: optomotor.py    License: GNU General Public License v3.0 8 votes vote down vote up
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() 
Example 3
Project: ddt4all   Author: cedricp   File: miniterm.py    License: GNU General Public License v3.0 7 votes vote down vote up
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 
Example 4
Project: plotink   Author: evil-mad   File: ebb_serial.py    License: MIT License 6 votes vote down vote up
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 
Example 5
Project: ethoscope   Author: gilestrolab   File: lynx_basics.py    License: GNU General Public License v3.0 6 votes vote down vote up
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() 
Example 6
Project: ethoscope   Author: gilestrolab   File: quality_control.py    License: GNU General Public License v3.0 6 votes vote down vote up
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() 
Example 7
Project: android3dblendermouse   Author: sketchpunk   File: miniterm.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 8
Project: nodemcu-uploader   Author: kmpm   File: serialutils.py    License: MIT License 6 votes vote down vote up
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) 
Example 9
Project: pyspinel   Author: openthread   File: extcap_ot.py    License: Apache License 2.0 6 votes vote down vote up
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() 
Example 10
Project: btlejack   Author: virtualabs   File: link.py    License: MIT License 6 votes vote down vote up
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() 
Example 11
Project: Openroast   Author: Roastero   File: tools.py    License: GNU General Public License v3.0 6 votes vote down vote up
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') 
Example 12
Project: i2cdriver   Author: jamesbowman   File: i2cgui.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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]) 
Example 13
Project: xArm-Python-SDK   Author: xArm-Developer   File: list_ports.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 
Example 14
Project: android_universal   Author: bkerler   File: miniterm.py    License: MIT License 6 votes vote down vote up
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 
Example 15
Project: axidraw   Author: evil-mad   File: ebb_serial.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 
Example 16
Project: axidraw   Author: evil-mad   File: ebb_serial.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 
Example 17
def printComPorts():
    logMessage('Available COM ports:')

    for i, port in enumerate(list_ports.comports()):
        logMessage('%d: %s' % (i+1, port.device))

    logOk('Done') 
Example 18
Project: apio   Author: FPGAwars   File: util.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 
Example 19
Project: nodemcu-pyflasher   Author: marcelstoer   File: Main.py    License: MIT License 5 votes vote down vote up
def _get_serial_ports():
        ports = [__auto_select__ + " " + __auto_select_explanation__]
        for port, desc, hwid in sorted(list_ports.comports()):
            ports.append(port)
        return ports 
Example 20
Project: web2board   Author: bq   File: util.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_serialports():
    try:
        from serial.tools.list_ports import comports
    except ImportError:
        raise exception.GetSerialPortsError(os.name)
    result = [{"port": p, "description": d, "hwid": h}
              for p, d, h in comports() if p]
    # fix for PySerial
    if not result and system() == "Darwin":
        for p in glob("/dev/tty.*"):
            result.append({"port": p, "description": "", "hwid": ""})
    return result 
Example 21
Project: pyvisa-py   Author: pyvisa   File: serial.py    License: MIT License 5 votes vote down vote up
def list_resources():
        return ["ASRL%s::INSTR" % port[0] for port in comports()] 
Example 22
Project: fermentrack   Author: thorrak   File: autoSerial.py    License: MIT License 5 votes vote down vote up
def find_all_serial_ports():
    """
    :return: a list of serial port info tuples
    :rtype:
    """
    all_ports = list_ports.comports()
    return iter(all_ports) 
Example 23
Project: intellij-micropython   Author: vlasovskikh   File: findusb.py    License: Apache License 2.0 5 votes vote down vote up
def find_devices(ids: List[Tuple[int, int]]) -> Iterable[str]:
    for port in comports():
        if (port.vid, port.pid) in ids:
            yield port.device 
Example 24
Project: intellij-micropython   Author: vlasovskikh   File: findusb.py    License: Apache License 2.0 5 votes vote down vote up
def main() -> None:
    opts = docopt(__doc__, argv=sys.argv[1:])
    vid_pid_list = opts['VID:PID']
    if vid_pid_list:
        ids = [parse_id(arg) for arg in sys.argv[1:]]
        for device in find_devices(ids):
            print(device)
    else:
        for port in comports():
            if port.vid is not None and port.pid is not None:
                print('%s: 0x%02x:0x%02x' % (port.device, port.vid, port.pid)) 
Example 25
Project: ddt4all   Author: cedricp   File: elm.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 
Example 26
Project: plotink   Author: evil-mad   File: ebb_serial.py    License: MIT License 5 votes vote down vote up
def list_port_info():
    # Find and return a list of all USB devices and their information.
    try:
        from serial.tools.list_ports import comports
    except ImportError:
        return None
    if comports:
        com_ports_list = list(comports())
        port_info_list = []
        for port in com_ports_list:
            port_info_list.append(port[0]) # port name
            port_info_list.append(port[1]) # Identifier
            port_info_list.append(port[2]) # VID/PID
        if port_info_list:
            return port_info_list 
Example 27
Project: RTGraph   Author: ssepulveda   File: Serial.py    License: MIT License 5 votes vote down vote up
def get_ports():
        """
        Gets a list of the available serial ports.
        :return: List of available serial ports.
        :rtype: str list.
        """
        if Architecture.get_os() is OSType.macosx:
            import glob
            return glob.glob("/dev/tty.*")
        else:
            found_ports = []
            for port in list(list_ports.comports()):
                Log.d(TAG, "found device {}".format(port))
                found_ports.append(port.device)
            return found_ports 
Example 28
Project: py9b   Author: etransport   File: serial.py    License: GNU General Public License v3.0 5 votes vote down vote up
def scan(self):
		ports = lp.comports()
		res = [("%s %04X:%04X" % (port.device, port.vid, port.pid), port.device) for port in ports]
		return res 
Example 29
Project: crazyflie-lib-python   Author: bitcraze   File: serialdriver.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_devices(self):
        result = {}
        for port in list_ports.comports():
            name = port.name
            # Name is not populated on all systems, fall back on the device
            if not name:
                name = port.device

            result[name] = port.device

        return result 
Example 30
Project: Jandroid   Author: FSecureLABS   File: miniterm.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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))