Get keyboard code for Python keypress

I am trying to get the keyboard code of a character pressed in python. To do this, I need to see if the keyboard number is pressed.

This is not what I'm looking for:

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

which displays the ascii code of the character. this means that I get the same address for keyboard 1 as normal 1. I also tried a similar setup using the library cursesand rawwith the same results.

I am trying to get the source code of a keyboard. How to do it?

+4
source share
3 answers

As the synthesizer said, I need to go to a lower level.

Using 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

This gives you the result: array('B', [0, 0, 0, 0, 0, 0, 0, 0])

pos:   0: (1 - , 2 - , 4 - , 8 - )   1:   2 -7: key code .

:

[3, 0 , 89, 90, 91, 92, 93, 94]

:

ctrl+shift+numpad1+numpad2+numpad3+numpad4+numpad5+numpad6

- , , .

+2

if you have opencv check this simple code:

`
import cv2, numpy as np
img = np.ones((100,100))*100
while True:
    cv2.imshow('tracking',img)
    keyboard = cv2.waitKey(1)   & 0xFF
    if keyboard !=255:
        print keyboard
    if keyboard==27 or keyboard==ord('q'):
        break
cv2.destroyAllWindows()`

Now, when a blank window opens, press any key on the keyboard. Hesam

0
source

All Articles