USB设备识别

8 投票
4 回答
45373 浏览
提问于 2025-04-15 20:39

我在使用Ubuntu 9.04的Python。假设我有两个USB设备连接在同一台电脑上。我该如何在Python代码中识别这些设备呢?比如像这样:

如果USB端口ID是A     就往设备1写数据 如果USB端口ID是B     就往设备2写数据

有什么想法吗……

4 个回答

2

我也在寻找答案,这里有一段可以用的代码:

def locate_usb():
    import win32file
    drive_list = []
    drivebits = win32file.GetLogicalDrives()
    for d in range(1, 26):
        mask = 1 << d
        if drivebits & mask:
            # here if the drive is at least there
            drname='%c:\\' % chr(ord('A') + d)
            t = win32file.GetDriveType(drname)
            if t == win32file.DRIVE_REMOVABLE:
                drive_list.append(drname)
    return drive_list

这段代码来自于 https://mail.python.org/pipermail/python-win32/2006-December/005406.html

5

@systempuntoout的回答很好,但今天我发现了一种更简单的方法来查找或遍历所有设备:usb.core.find(find_all=True)

接下来用你的例子:

import usb
for dev in usb.core.find(find_all=True):
    print("Device:", dev.filename)
    print("  idVendor: %d (%s)" % (dev.idVendor, hex(dev.idVendor)))
    print("  idProduct: %d (%s)" % (dev.idProduct, hex(dev.idProduct)))
15

你试过 pyUsb 吗?安装方法如下:

pip install pyusb

这里有一段你可以做的示例代码:

import usb
busses = usb.busses()
for bus in busses:
    devices = bus.devices
    for dev in devices:
        print("Device:", dev.filename)
        print("  idVendor: %d (0x%04x)" % (dev.idVendor, dev.idVendor))
        print("  idProduct: %d (0x%04x)" % (dev.idProduct, dev.idProduct))

这里

想要更多的文档,可以在 Python 的交互模式下使用 dir()help() 命令。

撰写回答