我在 ubuntu 9.04 上使用 python 说我有两个 USB 设备连接到一台 PC。我如何在 python 代码中识别设备.....例如
if usb port id == A 向设备 1 写入数据 if usb port id == B 向设备 2 写入数据
有任何想法吗....
你试过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))
这里有一个很好的 pyUsb 教程。
如需更多文档,请使用带有 dir() 和 help() 的 Python 交互模式。
@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))
好的,我也在谷歌搜索答案,这是有效的片段:
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
但无论如何..有人会在某个时候寻找答案:
我在 mac (osx 10.9) 上。我成功安装了带有 mac 端口的 libusb,但收到“没有可用的后端”消息。这是因为python找不到usb dylibs。
您必须将 libusb 的路径添加到 $DYLD_LIBRARY_PATH(例如 /opt/local/lib,无论您的 macport 安装在哪里)。
我一添加它,pyusb 就可以正常工作。