本帖最后由 蒜泥小德 于 2014-10-13 18:43 编辑
之前一直找不python的shell键盘捕捉方案显然input什么的都是要用回车配合的,于是看到了python-xlib。这个方法的好处是可以之间hook到键盘资源,可是也存在一些问题,就是操作其它窗口时需要ungrab键盘资源。
首先安装python-xlib
- sudo apt-get install python-xlib
复制代码
这里的例子就是用xlib做一个捕捉上下左右(以及wasd)的程序
- #!/usr/bin/env python
- from Xlib.display import Display
- from Xlib import X
- if __name__ == '__main__':
-
- display = Display()
- root = display.screen().root
- root.change_attributes(event_mask = X.KeyPressMask | X.KeyReleaseMask)
-
- ishooked = False
- while True:
- if False == ishooked:
- raw_input('Press ENTER to hook the keyboard, Press ESC to unhook it!')
- root.grab_keyboard(True, X.GrabModeAsync, X.GrabModeAsync, X.CurrentTime)
- ishooked = True
- print 'Please press ESC to unhook the keyboard!'
- else:
- event = display.next_event()
- if 2 == event.type:
- if 111 == event.detail or 25 == event.detail:
- print 'Up pressed'
- elif 116 == event.detail or 39 == event.detail:
- print 'Down pressed'
- if 113 == event.detail or 38 == event.detail:
- print 'Left pressed'
- elif 114 == event.detail or 40 == event.detail:
- print 'Right pressed'
- if 3 == event.type:
- if 111 == event.detail or 25 == event.detail or 116 == event.detail or 39 == event.detail:
- print 'Up Down Released'
- if 113 == event.detail or 38 == event.detail or 114 == event.detail or 40 == event.detail:
- print 'Left Rgiht Released'
-
- if 9 == event.detail:
- display.ungrab_keyboard(X.CurrentTime)
- display.flush()
- ishooked = False
复制代码
|