我有一些与无线USB数字小键盘交互的Python代码。我希望能够按名称发现设备,但显示为多个输入设备。在/dev/input/by-id
:
# ls -l /dev/input/by-id
total 0
lrwxrwxrwx 1 root root 9 Sep 25 14:30 usb-MOSART_Semi._2.4G_Keyboard_Mouse-event-kbd -> ../event0
lrwxrwxrwx 1 root root 9 Sep 25 14:30 usb-MOSART_Semi._2.4G_Keyboard_Mouse-if01-event-mouse -> ../event1
lrwxrwxrwx 1 root root 9 Sep 25 14:30 usb-MOSART_Semi._2.4G_Keyboard_Mouse-if01-mouse -> ../mouse0
使用evdev
模块:
>>> import evdev
>>> devices = [evdev.InputDevice(dev) for dev in evdev.list_devices()]
>>> for device in devices:
... print(device.fn, device.name)
...
/dev/input/event1 MOSART Semi. 2.4G Keyboard Mouse
/dev/input/event0 MOSART Semi. 2.4G Keyboard Mouse
显然,内核可以将-kbd
设备与-mouse
设备区分开来,但如何在我的代码中做出决定呢?我现在提出的解决方案利用了“键盘”设备包含KEY_KP...
功能的事实,所以我可以这样做:
def is_keyboard(device):
return evdev.ecodes.KEY_KP1 in device.capabilities()[evdev.ecodes.EV_KEY]
......但这似乎更像是一种启发式而非可靠的测试。有没有办法使用evdev
模块或替代方法检测给定的输入设备是键盘还是鼠标(或者两者中某些类似frankenstein的组合)?
答案 0 :(得分:0)
在evdev
中,似乎无法直接识别给定的输入设备是键盘还是鼠标。但您可以使用subprocess
作为替代方案。
import subprocess
process = subprocess.run("ls -l /dev/input/by-id", shell=True, stdout=subprocess.PIPE)
devices = process.stdout.decode().split("\n")[1:-1]
然后您可以获得如下列表:
[
"lrwxrwxrwx 1 root root 9 Sep 25 14:30 usb-MOSART_Semi._2.4G_Keyboard_Mouse-event-kbd -> ../event0",
"lrwxrwxrwx 1 root root 9 Sep 25 14:30 usb-MOSART_Semi._2.4G_Keyboard_Mouse-if01-event-mouse -> ../event1",
"lrwxrwxrwx 1 root root 9 Sep 25 14:30 usb-MOSART_Semi._2.4G_Keyboard_Mouse-if01-mouse -> ../mouse0"
]