欢迎访问宙启技术站
智能推送

使用get_device_from_id()函数查找特定ID的设备的Python代码示例

发布时间:2023-12-24 14:56:17

下面是一个使用get_device_from_id()函数查找特定ID的设备的Python代码示例:

import usb.core
import usb.util

def get_device_from_id(vendor_id, product_id):
    # 查找符合特定vendor ID和product ID的设备
    device = usb.core.find(idVendor=vendor_id, idProduct=product_id)
    if device is None:
        raise ValueError(f"Device {vendor_id}:{product_id} not found")

    return device

# 示例用法
vendor_id = 0x1234  # 替换为你要查找的设备的vendor ID
product_id = 0x5678  # 替换为你要查找的设备的product ID

try:
    device = get_device_from_id(vendor_id, product_id)
    # 对设备进行操作
    print("设备已找到")
except ValueError as e:
    print(e)

上述代码使用usb.core.find()函数来查找符合特定vendor ID和product ID的设备。如果设备不存在,则抛出一个ValueError异常。如果设备找到,可以在get_device_from_id()函数中的"对设备进行操作"的部分进行设备操作。

以下是使用示例:

假设需要查找vendor ID为0x1234,product ID为0x5678的设备。

vendor_id = 0x1234
product_id = 0x5678

try:
    device = get_device_from_id(vendor_id, product_id)
    # 对设备进行操作,例如读取/写入数据
    print(f"已找到设备: {device}")
except ValueError as e:
    print(e)

如果设备存在,则输出类似以下内容的信息:

已找到设备: <DEVICE ID 1234:5678 on Bus 001 Address 002>

如果设备不存在,则输出类似以下内容的错误信息:

Device 1234:5678 not found

请注意,上述示例中使用的vendor ID和product ID仅为示例,实际使用时需要根据你要查找的设备的详细信息进行替换。通过查阅设备的规范或文档,你可以找到设备的vendor ID和product ID。