获取Python中按键的键盘代码

yar*_*elk 5 python

我正在尝试获取在python中按下的字符的键盘代码。为此,我需要查看是否按了键盘数字。

这不是我要找的东西:

import tty, sys

tty.setcbreak(sys.stdin)

def main():
    tty.setcbreak(sys.stdin)
    while True:
        c = ord(sys.stdin.read(1))
        if c == ord('q'):
            break
    if c:
        print c
Run Code Online (Sandbox Code Playgroud)

输出字符的ASCII码。这意味着,我对键盘1的命令与普通键盘1的命令相同。我还尝试了使用curses库和进行类似的设置raw,并获得了相同的结果。

我正在尝试获取原始键盘代码。如何做到这一点?

yar*_*elk 2

正如synthesizerpatel所说,我需要进入一个较低的水平。

使用 pyusb:

import usb.core, usb.util, usb.control

dev = usb.core.find(idVendor=0x045e, idProduct=0x0780)

try:
    if dev is None:
        raise ValueError('device not found')

    cfg = dev.get_active_configuration()

    interface_number = cfg[(0,0)].bInterfaceNumber
    intf = usb.util.find_descriptor(
        cfg, bInterfaceNumber=interface_number)

    dev.is_kernel_driver_active(intf):
        dev.detach_kernel_driver(intf)


    ep = usb.util.find_descriptor(
        intf,
        custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_IN)

    while True:
        try:
            # lsusb -v : find wMaxPacketSize (8 in my case)
            a = ep.read(8, timeout=2000)
        except usb.core.USBError:
            pass
        print a
except:
    raise
Run Code Online (Sandbox Code Playgroud)

这会给你一个输出:array('B', [0, 0, 0, 0, 0, 0, 0, 0])

数组 pos: 0:修饰键的 AND(1 - 控制、2 - 移位、4 - 元、8 - 超级) 1:不知道 2 -7:按下的键的键代码。

所以:

[3, 0 , 89, 90, 91, 92, 93, 94]
Run Code Online (Sandbox Code Playgroud)

是:

ctrl+shift+numpad1+numpad2+numpad3+numpad4+numpad5+numpad6
Run Code Online (Sandbox Code Playgroud)

如果有人知道第二个索引存储什么,那就太棒了。