Python 相当于 OSX 的 evdev

Python evdev equivalent for OSX

我写了一个 python 脚本来轮询 evdev 以获取 HID 条形码扫描器(模拟键盘):该脚本在 Linux 平台 (Ubuntu) 上运行良好。是否有 evdev 的 OS X Python 等价物允许对现有 python 脚本进行少量移植?

如果您有 Python 经验并已将其配置为 HID 设备输入,请在回复中注明。

我猜 mac os 没有 evdev 端口,因为最后一个取决于 linux 内核。如果你想在 mac os 中的 HID 上实现一些业务逻辑,你应该使用评论中建议的一些高级抽象。但是如果你想要低级别的 evdev,我认为这样做的简单方法 using the Docker。我没有在 mac os 上使用 HID 设备的经验,但我用另一个驱动程序解决了同样的问题。

我使用 cython-hidapi 进行了一个简单的测试(可安装为 pip install hidapi - 请注意,这与评论中链接的不同,但功能似乎相似)。我还从 macports 安装了 hidapi-devel,但我不确定这是必要的,因为它在停用端口后继续工作。

通过修改示例try.py以使用微软USB无线keyboard/mouse设备的VID/PID如下

from __future__ import print_function

import hid
import time

print("Opening the device")

h = hid.device()
h.open(1118, 2048) # A Microsoft wireless combo keyboard & mouse

print("Manufacturer: %s" % h.get_manufacturer_string())
print("Product: %s" % h.get_product_string())
print("Serial No: %s" % h.get_serial_number_string())

try:
    while True:
        d = h.read(64)
        if d:
            print('read: "{}"'.format(d))
finally:
    print("Closing the device")
    h.close()

和运行 $ sudo python try.py我能够得到以下输出:

Opening the device
Manufacturer: Microsoft
Product: Microsoft® Nano Transceiver v2.0
Serial No: None
read: "[0, 0, 0, 0, 0, 0, 0, 0]"
read: "[0, 0, 0, 0, 0, 0, 0, 0]"
read: "[0, 0, 0, 0, 0, 0, 0, 0]"

--8<-- snip lots of repeated lines --8<--

read: "[0, 0, 0, 0, 0, 0, 0, 0]"
read: "[0, 0, 0, 0, 0, 0, 0, 0]"
read: "[0, 0, 21, 0, 0, 0, 0, 0]"
read: "[0, 0, 21, 0, 0, 0, 0, 0]"
read: "[0, 0, 21, 0, 0, 0, 0, 0]"
read: "[0, 0, 21, 0, 0, 0, 0, 0]"
read: "[0, 0, 0, 0, 0, 0, 0, 0]"
read: "[0, 0, 4, 0, 0, 0, 0, 0]"
read: "[0, 0, 4, 22, 0, 0, 0, 0]"
read: "[0, 0, 4, 22, 0, 0, 0, 0]"
read: "[0, 0, 4, 22, 0, 0, 0, 0]"
read: "[0, 0, 4, 22, 0, 0, 0, 0]"
read: "[0, 0, 4, 22, 0, 0, 0, 0]"
read: "[0, 0, 4, 0, 0, 0, 0, 0]"
read: "[0, 0, 4, 0, 0, 0, 0, 0]"
read: "[0, 0, 4, 9, 0, 0, 0, 0]"
read: "[0, 0, 4, 9, 0, 0, 0, 0]"
read: "[0, 0, 4, 9, 0, 0, 0, 0]"
read: "[0, 0, 4, 9, 0, 0, 0, 0]"
read: "[0, 0, 4, 9, 7, 0, 0, 0]"
read: "[0, 0, 4, 9, 7, 0, 0, 0]"
read: "[0, 0, 7, 0, 0, 0, 0, 0]"
^CClosing the device
Traceback (most recent call last):
  File "try.py", line 17, in <module>
    d = h.read(64)
KeyboardInterrupt

我正在使用的特定设备似乎枚举为键盘和鼠标等多个 HID 设备,所以你得到哪个似乎有点随机,但对于条形码扫描仪来说它应该很漂亮直截了当。