boppreh / keyboard

Hook and simulate global keyboard events on Windows and Linux.
MIT License
3.76k stars 433 forks source link

Timeout read_key() function #571

Open gitgrub opened 1 year ago

gitgrub commented 1 year ago

Is it possible to timeout the read_key() function? It blocks and I would like to release this block after a given time in seconds.

Maybe there is a slim pythonic way to do this?

gitgrub commented 1 year ago

Using windows here, in the meantime I do it like this to get a simple ASCII key:

import msvcrt

def clear_kbd_buffer():
    while msvcrt.kbhit():
        msvcrt.getch()

def get_key_timeout(timeout=5):
    start = time.time()
    clear_kbd_buffer()
    while True:
        if msvcrt.kbhit():
            k = msvcrt.getch()
            return k
        elif time.time() - start > timeout:
            return ""
        time.sleep(0.2)

key_timeout = 10
k = get_key_timeout(timeout=key_timeout)