python读取HID [英] python reading HID

查看:1139
本文介绍了python读取HID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个程序,该程序从连接到Linux系统的HID中获取输入并从中生成MIDI.我在MIDI方面还可以,但是在HID方面却很挣扎.尽管这种方法行之有效(取自此处):

I'd like to do a program that takes input from HIDs attached to a linux system and generates MIDI from those. I'm ok on the MIDI side, but I'm struggling on the HID side of things. While this approach works ok (taken from here):

#!/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的结构如何.

it gets high on CPU usage when there are lots of events; especially if tracking the mouse, large movements take almost 50% CPU on my system. I guess because of how the while is structured.

那么,在python中有更好的方法吗?我最好不要使用非维护或旧的库,因为我希望能够分发此代码并将其用于现代发行版(因此最终依赖性应该可以在最终用户的程序包管理器中轻松获得)

So, is there a better way to do this in python? I'd preferably like to not use non-maintained or old libraries, since I'd like to be able to distribute this code and have it working on modern distros (so eventual dependencies should easily be avaiable in package managers for end users)

推荐答案

有很多不符合您要求的事件.您必须按类型或代码过滤事件:

there are a lot of events that don't meet your requirements. you must filter events by type or code:

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)

这篇关于python读取HID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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