Search code examples
pythonpython-3.xpynput

Why this code is not printing Hi when the Enter key is pressed after stopping the code using F1 key?


from pynput import keyboard
import time
break_program = True
def on_press(key):
    global break_program
    print (key)
    if key == keyboard.Key.f1:
        print ('end pressed')
        break_program = False
        return True
    elif key == keyboard.Key.enter:
        print ('enter pressed')
        break_program = True
        return True
    else:
        return True
print("Press 'F1' key to stop the bot.")
print("Press enter to start the bot.")
with keyboard.Listener(on_press=on_press) as listener:
    while break_program == True:
        print('Hi')
        time.sleep(1)
    listener.join()

This code should stop running when F1 is pressed and should run when Enter is pressed.

On pressing Enter, it's getting into elif condition and printing enter pressed but not printing Hi as break_program is assigned back as True

Sample Output:

Press 'F1' key to stop the bot.
Press enter to start the bot.
Hi
Hi
Hi
Hi
Key.f1
end pressed
Key.enter
enter pressed

How the output should be:

Press 'F1' key to stop the bot.
Press enter to start the bot.
Hi
Hi
Hi
Hi
Key.f1
end pressed
Key.enter
enter pressed
Hi
Hi
...

Solution

  • You should use a non-block thread,and your code should be :

    from pynput import keyboard
    import time
    break_program = True
    def on_press(key):
        global break_program
        print (key)
        if key == keyboard.Key.f1 and break_program:
            print ('end pressed')
            break_program = False
    
        if key == keyboard.Key.enter:
            print ('enter pressed')
            break_program = True
    
    
    print("Press 'F1' key to stop the bot.")
    print("Press enter to start the bot.")
    
    listener =  keyboard.Listener(on_press=on_press)
    listener.start()
    while True:
        if break_program:
            print("Hi")
            time.sleep(1)