Ubuntu中使用pyUSB读取鼠标或键盘的数据程序

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

要注意的问题:

在ubuntu中USB的使用需要root权限。所以普通情况下即使程序没错也会导致USBError。解决的办法:在终端下以root方式打开python的IDE。Eclipse的pydev不能在root下打开,除非在root情况也装个pydev。最好是用spyder,虽然编辑起来没有eclipse方便,但是也很不错了。

如果程序运行错误而退出,会usb设备无反应,重新插拔usb即可。

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)

你可能感兴趣的:(ubuntu)