如何使用Python获取原始的USB键盘数据? [英] How can I get raw USB keyboard data with Python?

查看:496
本文介绍了如何使用Python获取原始的USB键盘数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Python中使用PyUSB,因为我将不得不监听USB端口以从电子卡中检索数据.目前,我必须通过读取连接到Raspberry-Pi的小键盘(USB连接)的直接输入来训练自己.当然,我不想读取键入的字符串,例如,我希望获得ASCII码.我只是不知道如何从USB键盘读取输入.

I am using PyUSB in Python as I will have to listen an USB port to retrieve data from an electronic card. For the moment, I have to train myself by reading direct input from a small keyboard (USB-connected) connected to a Raspberry-Pi. Of course, I do not want to read the typed String, I expect to get ASCII codes for example. I just don't get how I could read input from my USB-keyboard.

我已经找到了一些摘要:

I already found some snippets :

import usb.core
import usb.util

VENDOR_ID = 0x0922
PRODUCT_ID = 0x8003

# find the USB device
device = usb.core.find(idVendor=VENDOR_ID,
                       idProduct=PRODUCT_ID)

# use the first/default configuration
device.set_configuration()
# first endpoint
endpoint = device[0][(0,0)][0]

# read a data packet
attempts = 10
data = None
while data is None and attempts > 0:
    try:
        data = device.read(endpoint.bEndpointAddress,
                           endpoint.wMaxPacketSize)
    except usb.core.USBError as e:
        data = None
        if e.args == ('Operation timed out',):
            attempts -= 1
            continue

print data

我收到错误16设备正忙",或者如果我取消注释以下导致设备正忙"的行"device.set_configuration()",则什么也没有...(我确实替换了VENDOR_ID和PRODUCT_ID和我的键盘ID)

Either I get the error 16 "Device is busy" or nothing at all if I uncomment the following line "device.set_configuration()" which causes the "Device is busy" exception... (I did replace VENDOR_ID and PRODUCT_ID with my keyboard's ids)

推荐答案

我假设您正在使用Linux,就像您提到的Raspberry Pi.您可以使用 python-evdev 进行阅读/dev/input/中来自事件设备的数据.

I'm assuming that you are using Linux, as you mentioned the Raspberry Pi. You can use python-evdev to read data from the event devices in /dev/input/.

例如:

from evdev import InputDevice, categorize, ecodes

device = InputDevice("/dev/input/event3") # my keyboard
for event in device.read_loop():
    if event.type == ecodes.EV_KEY:
        print(categorize(event))

输出:

key event at 1462881252.506405, 30 (KEY_A), up
key event at 1462881252.541371, 31 (KEY_S), up
key event at 1462881252.616399, 31 (KEY_S), down
key event at 1462881252.674422, 22 (KEY_U), down
key event at 1462881252.730418, 31 (KEY_S), up
key event at 1462881252.745558, 22 (KEY_U), up
key event at 1462881252.808419, 50 (KEY_M), down
key event at 1462881252.914552, 23 (KEY_I), down
key event at 1462881252.925388, 50 (KEY_M), up
key event at 1462881253.003579, 49 (KEY_N), down
key event at 1462881253.066418, 34 (KEY_G), down

这篇关于如何使用Python获取原始的USB键盘数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆