Search code examples
pythonkeyboard

How can I check for a key press at any point during a loop?


I am trying to make a timer that counts down to 0, then starts counting up. I am using the time and keyboard modules. The keyboard module from PyPi.

Everything works as expected, and I am able to press a button to close the program, but it only works at the beginning of each iteration. Is there a way for it to check for a key press at any point while the loop is running? Do I need to be using a different module?

This is my code:

import time
import keyboard

m = 2
s = 0
count_down = True

while True:
    if keyboard.is_pressed('q'):
        break
    print(f"{m} minutes, {s} seconds")
    if count_down:
        if s == 0:
            m -= 1
            s = 60
        s -= 1
    elif not count_down:
        s += 1
        if s == 60:
            m += 1
            s = 0
    if m == 0 and s == 0:
        count_down = False
    time.sleep(1)

Solution

  • Using callback is common approach in such case, here is solution:

    import time
    import keyboard
    
    m = 2
    s = 0
    count_down = True
    
    break_loop_flag = False
    
    def handle_q_button():
        print('q pressed')
        global break_loop_flag
        break_loop_flag = True
    
    keyboard.add_hotkey('q', handle_q_button)
    
    while True:
        if break_loop_flag:
            break
        print(f"{m} minutes, {s} seconds")
        if count_down:
            if s == 0:
                m -= 1q
                s = 60
            s -= 1
        elif not count_down:
            s += 1
            if s == 60:
                m += 1
                s = 0
        if m == 0 and s == 0:
            count_down = False
        time.sleep(1)