2015-08-14 37 views
1

我正在與一些hardware.I使用USB-RS232轉換器的python GUI上工作。我不想要用戶在設備管理器中查找硬件的COM端口,然後在GUI中選擇端口號爲communication.How可以我的python代碼自動獲取端口號。對於特定的USB端口?我可以將硬件連接到特定的每個時間,如果我在其他PC上運行GUI,會發生什麼情況。您可以爲此提出任何其他解決方案。如何自動獲取端口號。在Python串行通信中的硬件?

在此先感謝!

回答

2

pyserial可以用他們的USB VID:PID編號列出端口。

from serial.tools import list_ports 
list_ports.comports() 

該函數返回一個元組,第3項是一個可能包含USB VID:PID號的字符串。你可以從那裏解析它。或者更好的,你可以使用grep功能也由list_ports模塊提供:

list_ports.grep("6157:9988") 

這個方法返回一個生成器對象,您可以遍歷。如果這是不可能的,有2個設備使用相同的VID連接:PID(我不認爲,但是出於測試目的,它的好),你只需做到這一點:

list_ports
my_port_name = list(list_ports.grep("0483:5740"))[0][0] 

文檔。

注意:我只在linux上測試過這個。 pyserial文檔警告說,在某些系統上可能不會列出硬件ID。

3

我假定您正在尋找一個COM端口,在設備管理器中描述爲USB到RS232,而不是想要列出所有可用的COM端口?

而且,你沒有提到你正在開發什麼操作系統上,或者你正在使用Python版本,但是這對我的作品使用Python 3.4在Windows系統上:

import serial.tools.list_ports 

def serial_ports(): 

    # produce a list of all serial ports. The list contains a tuple with the port number, 
    # description and hardware address 
    # 
    ports = list(serial.tools.list_ports.comports()) 

    # return the port if 'USB' is in the description 
    for port_no, description, address in ports: 
     if 'USB' in description: 
      return port_no