使用ctypes函数在python中绑定键事件

Rom*_*ome 6 python linux keyboard

我一直在尝试使用python将我的自定义事件绑定到具有特定事件代码编号的键盘事件,如下所示

ctypes.windll.user32.keybd_event( '0X24',0,2,0)

但正如你已经知道的那样

WINDLL

该库仅适用于Windows操作系统.我怎么能在Linux机器上做这样的事情?我读到了

CDLL( 'libc.so.6的')

但是我不明白这个图书馆是否有用?

是否有另一种方法使用虚拟键代码使用python在OS级别设置keypress侦听器?

obg*_*naw 5

Linux输入子系统由三部分组成:驱动层、输入子系统核心层和事件处理层。并且键盘或其他输入事件都由 描述input_event

使用以下代码并输入您的终端 python filename.py | grep "keyboard"

#!/usr/bin/env python
#coding: utf-8
import os

deviceFilePath = '/sys/class/input/'

def showDevice():
    os.chdir(deviceFilePath)
    for i in os.listdir(os.getcwd()):
        namePath = deviceFilePath + i + '/device/name'
        if os.path.isfile(namePath):
            print "Name: %s Device: %s" % (i, file(namePath).read())

if __name__ == '__main__':
    showDevice()
Run Code Online (Sandbox Code Playgroud)

你应该得到Name: event1 Device: AT Translated Set 2 keyboard。然后使用

#!/usr/bin/env python
#coding: utf-8
from evdev import InputDevice
from select import select

def detectInputKey():
    dev = InputDevice('/dev/input/event1')

    while True:
        select([dev], [], [])
        for event in dev.read():
            print "code:%s value:%s" % (event.code, event.value)


if __name__ == '__main__':
    detectInputKey()
Run Code Online (Sandbox Code Playgroud)

evdev是一个包,提供与 Linux 中通用输入事件接口的绑定。evdev 接口用于将内核中生成的事件通过通常位于 /dev/input/.and selectis 中的字符设备直接传递到用户空间select