我问的原因是,现在我使用'by-id‘字符串引用端口。‘’by id‘指的是串行设备的序列号。
这很好,但如果我想用完全相同的品牌和型号替换该串行设备怎么办?它不会工作,因为每个串行设备都有一个唯一的序列号。
也许有更好的方法可以做到这一点?顺便说一下这个串行设备是个条形码扫描器。
发布于 2016-08-03 13:51:32
因此,对于那些希望完成与我相同的任务的人来说,这是我找到的通过供应商id (VID)和产品id (PID)来引用串行设备的最佳方式。
还请注意,以下代码需要pyserial版本3或更高版本。
from serial.tools import list_ports
VID = 1234
PID = 5678
device_list = list_ports.comports()
for device in device_list:
if (device.vid != None or device.pid != None):
if ('{:04X}'.format(device.vid) == VID and
'{:04X}'.format(device.pid) == PID):
port = device.device
break
port = None
发布于 2021-04-16 13:36:58
我发现list_ports.grep
函数用起来很方便,比如
import serial.tools.list_ports as list_ports
device_signature = '0403:6014'
def find_serial_device():
"""Return the device path based on vender & product ID.
The device is something like (like COM4, /dev/ttyUSB0 or /dev/cu.usbserial-1430)
"""
candidates = list(list_ports.grep(device_signature))
if not candidates:
raise ValueError(f'No device with signature {device_signature} found')
if len(candidates) > 1:
raise ValueError(f'More than one device with signature {device_signature} found')
return candidates[0].device
https://stackoverflow.com/questions/38661797
复制相似问题