python从键盘读取数据_如何使用Python获取原始的USB键盘数据?

1586010002-jmsa.png

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

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)

解决方案

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/.

For example:

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))

Output:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值