Ubuntu中使用pyUSB讀取鼠標或鍵盤的數據程序

參考 :http://www.orangecoat.com/how-to/read-and-decode-data-from-your-mouse-using-this-pyusb-hackpython

要注意的問題:ubuntu

在ubuntu中USB的使用須要root權限。因此普通狀況下即便程序沒錯也會致使USBError。解決的辦法:在終端下以root方式打開python的IDE。Eclipse的pydev不能在root下打開,除非在root狀況也裝個pydev。最好是用spyder,雖然編輯起來沒有eclipse方便,可是也很不錯了。eclipse

若是程序運行錯誤而退出,會usb設備無反應,從新插拔usb便可。this

import usb
dev = usb.core.find(idVendor= 0x24ae, idProduct = 0x2000)
cfg = dev.get_active_configuration()
intf = cfg[(0,0)]
interface = 0
endpoint = dev[0][(0,0)][0]
if dev.is_kernel_driver_active(interface) is True:
    dev.detach_kernel_driver(interface)
    usb.util.claim_interface(dev, interface)
collected = 0
attempts = 50
while collected <attempts:
    try:
        data = dev.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize)
        collected += 1
        print data
    except usb.core.USBError as e:
        data = None
        if e.args == ('Operation timed out',):
            continue
usb.util.release_interface(dev, interface)
dev.attach_kernel_driver(interface)
相關文章
相關標籤/搜索