我想获得连接到COM端口的设备列表。例如,我没有输出python -m serial.tools.list_ports
的COM1 COM2
,而是希望得到像Arduino_Uno Arduino Due
等的输出(例如,像Arduino Gui那样做)。
我找到了一些列出COM端口的答案(如Listing available com ports with Python),但我的问题没有答案。
@J.P。彼得森是对的 - 串口本身并不提供这些信息。但USB规范允许一些信息被偷偷进入,而且serial.tools.list_ports.comports()值得回报。以下代码剪切来自我的ArduinoBase类,该类在Windows和Linux下运行,并且可以满足您的要求,即它可以为您提供Arduino Uno和Arduino Due描述。
def listPorts():
"""!
@brief Provide a list of names of serial ports that can be opened as well as a
a list of Arduino models.
@return A tuple of the port list and a corresponding list of device descriptions
"""
ports = list( serial.tools.list_ports.comports() )
resultPorts = []
descriptions = []
for port in ports:
if not port.description.startswith( "Arduino" ):
# correct for the somewhat questionable design choice for the USB
# description of the Arduino Uno
if port.manufacturer is not None:
if port.manufacturer.startswith( "Arduino" ) and \
port.device.endswith( port.description ):
port.description = "Arduino Uno"
else:
continue
else:
continue
if port.device:
resultPorts.append( port.device )
rdescriptions.append( str( port.description ) )
return (resultPorts, descriptions)