Home > Enterprise >  How do I take keyboard input without a while loop?
How do I take keyboard input without a while loop?

Time:09-28

I know how to get key input directly with the keyboard module but it needs a while loop around it specifically. if I use this in my code obviously it stops it in its tracks!

while True:
    event = keyboard.read_event()
    if event.event_type == keyboard.KEY_DOWN:
        print(event.name)

CodePudding user response:

Use a keyboard.listener in a non-blocking fashion (not in a with statement), as per the documentation:

from pynput import keyboard

def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.esc:
        # Stop listener
        return False

# ...or, in a non-blocking fashion:
listener = keyboard.Listener(
    on_press=on_press,
    on_release=on_release)
listener.start()

# execution immediately continues past listener.start()

When using the non-blocking version above, the current thread will continue executing. This might be necessary when integrating with other GUI frameworks that incorporate a main-loop, but when run from a script, this will cause the program to terminate immediately.

  • Related