【发布时间】:2011-01-30 00:44:36
【问题描述】:
我在 ubuntu 9.04 上使用 python 假设我有两个 USB 设备连接到一台 PC。我如何在 python 代码中识别设备.....例如
如果 USB 端口 ID == A 将数据写入设备 1 如果 USB 端口 ID == B 向设备2写入数据
任何想法....
【问题讨论】:
标签: python controls port device
我在 ubuntu 9.04 上使用 python 假设我有两个 USB 设备连接到一台 PC。我如何在 python 代码中识别设备.....例如
如果 USB 端口 ID == A 将数据写入设备 1 如果 USB 端口 ID == B 向设备2写入数据
任何想法....
【问题讨论】:
标签: python controls port device
你试过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))
HerepyUsb的好教程。
如需更多文档,请使用带有 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))
【讨论】:
但无论如何..有人会在某个时候寻找答案:
我在 mac (osx 10.9).. 我成功地安装了带有 mac 端口的 libusb,但收到“没有可用的后端”消息。这是因为python找不到usb dylibs。
您必须将 libusb 的路径添加到您的 $DYLD_LIBRARY_PATH(例如 /opt/local/lib,无论您的 macport 安装在哪里)。
我一添加它,pyusb 就可以正常工作了。
【讨论】:
brew install libusb
好的,我也在谷歌搜索答案,这里是 sn-p 的工作原理:
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
【讨论】: