问题描述
我需要使用Python通过USB发送数据,我正在使用PyUSB(http://sourceforge.net/apps/trac/pyusb/)我寻找任何可用的USB端口,并尝试发送一条消息:
I need to send data via USB using Python, I'm using PyUSB (http://sourceforge.net/apps/trac/pyusb/)I look for any USB port available, and I tried to send a message:
devList = usb.core.find(find_all=True)
for dev in devList:
for cfg in dev:
for intf in cfg:
sys.stdout.write('\t' + str(intf.bInterfaceNumber) + ',' + str(intf.bAlternateSetting) + '\n')
for ep in intf:
sys.stdout.write('\t\t' + str(ep.bEndpointAddress) + '\n')
if ep.bEndpointAddress:
try:
dev.write(ep.bEndpointAddress, 'test', intf.bInterfaceNumber)
except Exception:
print "\t\terror : dev.write("+str(ep.bEndpointAddress)+", 'test', "+str(intf.bInterfaceNumber)+")"
结果是:
0,0
129
error : dev.write(129, 'test', 0)
0,1
129
error : dev.write(129, 'test', 0)
0,0
136
error : dev.write(136, 'test', 0)
10
error : dev.write(10, 'test', 0)
1,0
139
error : dev.write(139, 'test', 1)
13
error : dev.write(13, 'test', 1)
如果没有尝试,它会给出:
without try catch it gives:
usb.core.USBError: [Errno None] usb_claim_interface: could not claim interface 0, invalid configuration 0
怎么了?有没有通过python与USB通信的最佳方法?因为我刚刚找到了这个库
What is wrong? Is there a best way to communicate via usb with python? because I just have found this lib
推荐答案
如教程中所述:
显然,大多数情况下只有一种配置.假设所有这些配置都来自不同的设备,则可以执行以下操作:
Apparently most of the times there is only one configuration. Assuming all those configurations are from different devices, you can do something like:
for dev in devList:
for cfg in dev:
cfg.set()
for intf in cfg:
如果由于资源繁忙"而无法设置配置,则需要卸载其接口内核驱动程序:
If you can't set a configuration due to "resource busy", you'll need to unload its interface kernel driver:
dev.detatch_kernel_driver(interface)
这篇关于使用PyUSB通过USB发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!