Skip to content Skip to sidebar Skip to footer

Real-time Capture And Processing Of Keypresses (e.g. Keypress Event)

Note: I want to do this without using any external packages, like PyGame, etc. I am attempting to capture individual keypresses as they arrive and perform an action for specific ch

Solution 1:

First off, I don't really thing you need multithreading. You'd need that if you, for example, wanted to do some tasks like drawing on screen or whatever and capturing keys while you do this.

Let's consider a case where you only want to capture keys and after each keypress execute some action: Exit, if x was pressed, otherwise just print the character. All you need for this case is simple while loop

def process(key):
    ifkey == 'x':exit('exitting')else:
        print(key, end="", flush=True)

if __name__ == "__main__":
    whileTrue:
        key = getch()
        process(key)

Notice absence of sleep(). I am assuming you thought getch() won't wait for user input so you set 1s sleep time. However, your getch() waits for one entry and then returns it. In this case, global variable is not really useful, so you might as well just call process(getch()) inside the loop.

print(key, end="", flush=True) => the extra arguments will ensure pressed keys stay on one line, not appending newline character every time you print something.

The other case, where you'd want to execute different stuff simultaneously, should use threading.

Consider this code:

n = 0
quit = Falsedefprocess(key):
    if key == 'x':
        global quit
        quit = True
        exit('exitting')
    elif key == 'n':
        global n
        print(n)
    else:
        print(key, end="", flush=True)

defkey_capturing():
    whileTrue:
        process(getch())

if __name__ == "__main__":
    threading.Thread(target=key_capturing).start()
    whilenot quit:
        n += 1
        time.sleep(0.1)

This will create global variable n and increment it 10 times a second in main thread. Simultaneously, key_capturing method listens to keys pressed and does the same thing as in previous example + when you press n on your keyboard, current value of the global variable n will be printed.

Closing note: as @zondo noted, you really missed braces in the getch() definition. return msvcrt.getch should most likely be return msvcrt.getch()

Post a Comment for "Real-time Capture And Processing Of Keypresses (e.g. Keypress Event)"