我有一些与无线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的组合)?
似乎无法直接识别给定的输入设备是键盘还是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"
]