How to bind a function to a keyboard button in Python?

I wrote a bot using the pyautogui library. It is necessary that when you press the button (for example, 'enter'), the bot is played cyclically, and when you press it again, it either forcibly stops, or the program closes.

I searched for a long time for information on this topic and did not find it. Maybe someone knows the solutions?

Example of a bot:

import pyautogui as root
from time import sleep
    
sleep (3)
root.moveTo( 242, 177 )
root.doubleClick()
sleep (17)
root.moveTo( 1709, 177 )  
root.click()
Author: Jack_oS, 2020-12-30

1 answers

As suggested in the comments, use keyboard


import keyboard

def on_triggered():
    print("Ваша функция!!!")

keyboard.add_hotkey('ctrl+shift', on_triggered)


print("Нажмите ESC для остановки")
keyboard.wait('esc')
print("Программа идет дальше... )') # отработает после нажатия esc

Or the same thing but with threads:

def on_triggered():
    print("Ваша функция!!!")

def key_watcher():
    keyboard.add_hotkey('ctrl+shift', on_triggered)
    keyboard.wait('esc')

thread_ = threading.Thread(target=key_watcher)
thread_.start()
print("Программа идет дальше... )') # отработает сразу при запуске программы

Thus, the interception of keyboard presses wrapped in a stream does not block the operation of the main program.

 2
Author: Kers, 2020-12-30 16:02:34