我一直在尝试使用 python 将我的自定义事件绑定(bind)到具有特定事件代码编号的键盘事件,如下所示
ctypes.windll.user32.keybd_event('0x24',0,2,0)
但是你已经知道了
windll
该库仅适用于 Windows 操作系统。 我怎样才能在 Linux 机器上做这样的事情? 我读过
CDLL('libc.so.6')
但我不知道这个库是否有用?
是否有另一种方法可以使用虚拟键码在操作系统级别使用 python 设置按键监听器?
最佳答案
Linux输入子系统由三部分组成:驱动层、输入子系统核心层和事件处理层。
而键盘或其他输入事件都由input_event
描述。
使用下面的代码并在终端中输入 python filename.py | grep“键盘”
#!/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()
您应该得到名称:event1 设备: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()
evdev
是一个为 Linux 中的通用输入事件接口(interface)提供绑定(bind)的包。 evdev 接口(interface)用于将内核中生成的事件通过通常位于/dev/input/中的字符设备直接传递到用户空间。select
是 select
。
关于python - 使用ctypes函数在python中绑定(bind)键事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47412460/