Почему этот код не печатается Привет, когда клавиша Enter нажата после остановки кода клавишей F1? - PullRequest
0 голосов
/ 21 марта 2020
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()

Этот код должен прекратить выполнение при нажатии F1 и должен работать при нажатии Enter.

При нажатии Enter он попадает в состояние elif и печатает enter pressed но не печатать Hi, поскольку break_program назначается обратно как True

Пример вывода:

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

Как должен быть вывод:

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
...

1 Ответ

1 голос
/ 21 марта 2020

Вы должны использовать неблокированный поток, и ваш код должен быть:

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)
...