• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python list_ports.comports函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中serial.tools.list_ports.comports函数的典型用法代码示例。如果您正苦于以下问题:Python comports函数的具体用法?Python comports怎么用?Python comports使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了comports函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: connect_serial

def connect_serial(port, baudrate=115200, timeout=1, writeTimeout=1):
    """
    Return Serial object after making sure that the port is accessible and that the port is expressed as a string.

    :param port: str or int (ie "COM4" or 4 for Windows).
    :param baudrate: baudrate.
    :param timeout: read timeout in seconds, default 1 sec.
    :param writeTimeout: write timeout in seconds, default 1 sec.
    :return: serial port object.
    :rtype: serial.Serial
    """

    if isinstance(port, int):
        port = "COM{0}".format(port)
    names_list = list()
    for i in list_ports.comports():
        names_list.append(i[0])
    if port not in names_list:
        print ("Serial not found on {0}.".format(port))
        print ("Listing current serial ports with devices:")
        for ser in list_ports.comports():
            ser_str = "\t{0}: {1}".format(ser[0], ser[1])
            print ser_str
        time.sleep(0.01)  # just to let the above lines print before the exemption is raised. cleans console output.
        raise serial.SerialException("Requested COM port: {0} is not listed as connected.".format(port))
    else:
        return serial.Serial(port, baudrate=baudrate, timeout=timeout, writeTimeout=writeTimeout)
开发者ID:olfa-lab,项目名称:olfactometry,代码行数:27,代码来源:utils.py


示例2: locateport

def locateport():
    """
    Function Name:  locateport()
    Input Args:     None
    Output:         port        The port at which the arduino is connected
    Description:    This function checks th OS it is running on and
    also identifies the com port the ARDUINO BOARD is connected to.
    And also returns the COM port the ARDUINO BOARD is connected.
    """
    port = ''
    if sys.platform.startswith('win'):      # For WINDOWS
        # port = ''
        ports = list(comports())
        for i in ports:
            for j in i:
                if 'Arduino' in j:
                    port = i[0]

    elif sys.platform.startswith('linux'):  # For LINUX
        b = []
        # port = ''
        ports = list(comports())
        for i in range(len(ports)):
            for x in range(7):
                portname = "/dev/ttyACM"+str(x)
                if ports[i][0] == portname:
                    b.append(ports[i][0])
        port = b[0]
    return port
开发者ID:Akash3hk,项目名称:Scilab-Arduino-Project-FOSSEE-Internship,代码行数:29,代码来源:pyarduino.py


示例3: comportRefresh

	def comportRefresh(self, dbg=False):
		#Detect devices
		hwgrep = []
		for i in comports():
			if dbg:
				#Print list to console if requested
				comport = ''
				for j in i: comport+=j+"\t"
				print(comport)
			for hw in i[2].split(' '):
				hwgrep += ["hwgrep://"+hw+"\t"+i[1]]

		#Populate combobox
		devices = sorted([x[0]+"\t"+x[1] for x in comports()])
		devices += ['']
		devices += sorted(set(hwgrep))
		devices += ['']
		devices += sorted(["spy://"+x[0]+"?raw"+"\t(Debug) "+x[1] for x in comports()])
		devices += ['', 'socket://localhost:23', 'rfc2217://localhost:2217']

		#Clean neighbour duplicates
		devices_clean = []
		devprev = '';
		for i in devices:
			if i.split("\t")[0] != devprev: devices_clean += [i]
			devprev = i.split("\t")[0]

		self.portCombo.fill(devices_clean)
开发者ID:ThierryM,项目名称:bCNC,代码行数:28,代码来源:FilePage.py


示例4: find_serial_port

    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...")
开发者ID:HackerSchool,项目名称:HES,代码行数:33,代码来源:controller_communication.py


示例5: get_port

    def get_port(self):
        """Detect Buspirate and return first detected port
        
        Returns
        -------
        str
            First valid port name
        """
        try:
            import serial.tools.list_ports as list_ports
        except ImportError:
            raise ImportError('Pyserial version with serial.tools.list_port required')

        import serial

        # the API in version 2 and 3 is different
        if serial.VERSION[0] == '2':
            ports = list_ports.comports()
            for port in ports:
                if len(port) == 3 and '0403:6001' in port[2]:
                    return port[0]
                if len(port) == 3 and 'VID_0403+PID_6001' in port[2]:
                    return port[0]
        else:
            ports = list_ports.comports()
            for port in ports:
                if hasattr(port, 'pid') and hasattr(port, 'vid'):
                    if port.vid == 1027 and port.pid == 24577:
                        return port.device
开发者ID:audiohacked,项目名称:pyBusPirateLite-1,代码行数:29,代码来源:base.py


示例6: list_com_ports

def list_com_ports():
    port_list = list_ports.comports()    
    if port_list is not None and len(port_list) is not 0:
        print "Available Serial ports - "
        for port in list_ports.comports():
            print "\t"+port[0]
    else:
        print "No serial ports found by pySerial - you might be using cygwin where you can use /dev/ttySXX where XX = (nn-1) with nn being the COM port number (so COM11 is /dev/ttyS10)"
开发者ID:Srinivas-E,项目名称:sc_multi_uart,代码行数:8,代码来源:s2e_test.py


示例7: refresh

 def refresh(self):
     self.portComboBox.setStyleSheet('QComboBox {color: black;}')
     ports = list_ports.comports()
     if ports != self.ports:
         self.ports = ports
         self.portComboBox.clear()
         for port in list_ports.comports():
             name = port[0]
             if name.startswith('/dev/ttyACM') or name.startswith('/dev/ttyUSB') or name.startswith('COM'):
                 self.portComboBox.addItem(name)
开发者ID:qunanan,项目名称:pqcom,代码行数:10,代码来源:pqcom.py


示例8: refresh

 def refresh(self):
     self.portComboBox.setPalette(self.originalPalette)
     ports = list_ports.comports()
     if ports != self.ports:
         self.ports = ports
         self.portComboBox.clear()
         for port in list_ports.comports():
             name = port[0]
             if name.startswith('/dev/ttyACM') or name.startswith('/dev/ttyUSB') or name.startswith('COM'):
                 self.portComboBox.addItem(name)
开发者ID:fatman2021,项目名称:pqcom,代码行数:10,代码来源:pqcom.py


示例9: get_serial_ports

def get_serial_ports():
    '''
    Returns a list object for all available serial ports
    '''
    if os.name == 'nt':
        # windows
        _comports = [port for port in list_ports.comports()]
        if _comports.__len__()>0:
            _serial_ports = ['\\\\.\\'+port[0] for port in list_ports.comports()]
        else:
            _serial_ports = []
    else:
        # unix
        _serial_ports = [port[0] for port in list_ports.comports()]
    return _serial_ports
开发者ID:latchdevel,项目名称:latch-moneybox,代码行数:15,代码来源:MoneyBox.py


示例10: serial_ports

def serial_ports():
    '''
    Returns a generator for all available serial ports
    '''
    if os.name == 'nt':
        # windows
        _comports = [port for port in list_ports.comports()]
        if _comports.__len__()>0:
            _serial_ports = [p for p in _comports[0]]
        else:
            _serial_ports = []
    else:
        # unix
        _serial_ports = [port[0] for port in list_ports.comports()]
    return _serial_ports
开发者ID:Jucker,项目名称:SIPIntercom-with-FPS,代码行数:15,代码来源:FPS2.py


示例11: find_tty

    def find_tty(self):
        for port in comports():
            print port
            if re.search(r'PID=2458:0*1', port[2]):
                return port[0]

        return None
开发者ID:chitrang6,项目名称:CMPE_220_CrazyFlie,代码行数:7,代码来源:myo.py


示例12: scan_for_device

    def scan_for_device(self):
        ports = [x[0] for x in list_ports.comports()]
        retport = None
        self._log("Searching for an active bootloader")

        for p in ports:
            try:
                rsp = self._send_ping(p)
                if not rsp == None:
                    ver = self._get_version(p)
                    if not ver:
                        version = '<=0.1.2'
                    else:
                        version = '.'.join(
                            [str(x) for x in
                             (ver.major, ver.minor, ver.bugfix)])
                    self._log("Found bootloader ver: {} on: {}".format(version, p))
                    retport = p
                    break
                else:
                    raise IOError()
            except IOError:
                pass

        return retport
开发者ID:autosportlabs,项目名称:ASL_F4_bootloader,代码行数:25,代码来源:fw_update.py


示例13: ask_for_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.
    """

    try:
        raw_input
    except NameError:
        raw_input = input   # in python3 it's "raw"
        unichr = chr

    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 [1]: ') or 1
        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
开发者ID:ytmytm,项目名称:ksp-gegi,代码行数:31,代码来源:ask_for_port.py


示例14: _port_search

 def _port_search(self):
     print 'Automatically detecting COM ports.'
     ports = list(comports())
     print 'Detected %i ports.' % len(ports)
     port = ports[0][0]
     print 'Trying port ' + port + '.'
     return port
开发者ID:lewisamarshall,项目名称:keithley,代码行数:7,代码来源:device.py


示例15: find_port

 def find_port(self):
     a = list(list_ports.comports())
     for portStruct in a:
         m = re.search('(/dev/cu\.usbmodem.*)', portStruct[0])
         if m:
             print "found port: ", m.group(0)
             return m.group(0)
开发者ID:aerringer,项目名称:TeensyMotor,代码行数:7,代码来源:TeensyMotor.py


示例16: scanComPort

 def scanComPort(self):
     port_list=list(list_ports.comports())
     num=len(port_list)
     #print 'num=', num
     for i in xrange(num):
         str=port_list[i][2].split('=')
         #print str
         if(str[0]=='USB VID:PID'):
             str=str[1].split(' ')[0] #Extract VID and PID from string.
             str=str.split(':')
             print str
             if(str[0] in usb_id):
                 if(str[1].lower() in usb_id[str[0]]):
                     port=port_list[i][0]
                     try:
                         __port = serial.Serial(port, baudrate=38400, bytesize=8, parity ='N', stopbits=1, xonxoff=False, dsrdtr=False, timeout=5)
                     except serial.SerialException, e:
                         print e.message
                         continue
                     time.sleep(0.5)
                     while(True):
                         num=__port.inWaiting()
                         if(num==0):
                             break
                         else:
                             print '-',
                         __port.flushInput()  #Clear input buffer.
                         time.sleep(0.1)
                     __port.close()
                     return port
开发者ID:OpenWave-GW,项目名称:OpenWave-2KE,代码行数:30,代码来源:gw_com.py


示例17: __init__

 def __init__(self):
     wx.Dialog.__init__(
         self, None, title="DAQControl",
         style=(wx.STAY_ON_TOP | wx.CAPTION))
     self.horizontal_sizer = wx.BoxSizer(wx.HORIZONTAL)
     self.vertical_sizer = wx.BoxSizer(wx.VERTICAL)
     self.gauge = wx.Gauge(self, range=100, size=(100, 15))
     self.horizontal_sizer.Add(self.gauge, wx.EXPAND)
     avaiable_ports = list(comports())
     self.sample_list = []
     if len(avaiable_ports) != 0:
         for nombre in avaiable_ports:
             self.sample_list.append(nombre[0])
     self.label_hear = wx.StaticText(self, label="Select Serial Port")
     self.edit_hear = wx.ComboBox(
         self, size=(95, -1), choices=self.sample_list,
         style=wx.CB_READONLY)
     self.edit_hear.SetSelection(0)
     self.horizontal_sizer.Add(self.label_hear, wx.EXPAND)
     self.horizontal_sizer.Add(self.edit_hear, wx.EXPAND)
     self.button_ok = wx.Button(self, label="OK")
     self.Bind(wx.EVT_BUTTON, self.ok_event, self.button_ok)
     self.button_cancel = wx.Button(self, label="Cancel", pos=(115, 22))
     self.Bind(wx.EVT_BUTTON, self.cancel_event, self.button_cancel)
     self.vertical_sizer.Add(self.horizontal_sizer, wx.EXPAND)
     self.vertical_sizer.Add(self.button_ok, wx.EXPAND)
     self.gauge.Show(False)
     self.SetSizer(self.vertical_sizer)
     self.SetAutoLayout(1)
     self.vertical_sizer.Fit(self)
开发者ID:vmlenart,项目名称:opendaq-gui,代码行数:30,代码来源:main.py


示例18: ListAllPorts

    def ListAllPorts():
        portsList = []
        allSerial = list_ports.comports()
        for ser in allSerial:
            portsList.append(ser[0])

        return portsList
开发者ID:yougukepp,项目名称:flyer,代码行数:7,代码来源:serial.py


示例19: serial_ports

def serial_ports():
    """
    Returns a generator for all available serial ports
    based on: http://stackoverflow.com/questions/12090503/listing-available-com-ports-with-python
    WARNING: works with pyserial>=2.7
    """

    ports = []
    if os.name == 'nt':
        # windows
        for i in range(256):
            try:
                s = serial.Serial(i)
                s.close()
                ports.append('COM' + str(i + 1))
            except serial.SerialException:
                pass
    else:
        # unix
        for port in list_ports.comports():
            if 'USB' in port[0] or 'ACM' in port[0]:
                # yield port[0]
                ports.append(port[0])

    return ports
开发者ID:SteveNguyen,项目名称:pypot,代码行数:25,代码来源:io.py


示例20: list_serial_ports

 def list_serial_ports(self):
     try:
         ports = list(comports())
     except Exception, e:
         if comports != win32_comports_bruteforce:
             LOG.error("Failed to detect win32 serial ports: %s" % e)
             ports = win32_comports_bruteforce()
开发者ID:tylert,项目名称:chirp.hg,代码行数:7,代码来源:platform.py



注:本文中的serial.tools.list_ports.comports函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python serial_manager.SerialManager类代码示例发布时间:2022-05-27
下一篇:
Python serial.Serial类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap