python 读取 HID

3 投票
1 回答
2357 浏览
提问于 2025-04-16 23:17

我想写一个程序,可以从连接到Linux系统的HID设备(比如键盘、鼠标)获取输入,然后把这些输入转换成MIDI信号。我对MIDI的部分还算可以,但在处理HID这块我遇到了一些困难。虽然我找到了一种方法(来自这里):

#!/usr/bin/python2
import struct

inputDevice = "/dev/input/event0" #keyboard on my system
inputEventFormat = 'iihhi'
inputEventSize = 16

file = open(inputDevice, "rb") # standard binary file input
event = file.read(inputEventSize)
while event:
  (time1, time2, type, code, value) = struct.unpack(inputEventFormat, event)
  print type,code,value
  event = file.read(inputEventSize)
file.close()

但是当事件很多的时候,这个方法会导致CPU使用率很高;尤其是当我追踪鼠标时,鼠标大幅移动几乎会占用我系统50%的CPU。我想这可能和while循环的结构有关。

那么,有没有更好的方法可以用Python来实现这个功能呢?我希望能使用一些维护良好、比较新的库,因为我想把这个代码分享出去,让它在现代的Linux发行版上也能正常工作(这样最终用户在包管理器中能轻松找到所需的依赖库)。

1 个回答

1

有很多事件不符合你的要求。你需要根据类型或代码来筛选这些事件:

while event:
  (time1, time2, type, code, value) = struct.unpack(inputEventFormat, event)
  if type==X and code==Y:
    print type,code,value
  event = file.read(inputEventSize)

撰写回答