'How to exit a loop when any key is pressed?

I would like Python to run the following code in a loop e.g.

while(True): 
   pyautogui.moveTo(844,222)
   pyautogui.click(interval=2)

until ANY button is pressed so that the logic can continue as follows:

if keyboard.is_pressed("1"):
    pyautogui.moveTo(1021,308)
    pyautogui.click()
    pyautogui.moveTo(958,771)
    pyautogui.click()
    pyautogui.moveTo(961,531)
    
if keyboard.is_pressed("2"):
    pyautogui.moveTo(1446,308)
    pyautogui.click()
    pyautogui.moveTo(958,771)
    pyautogui.click()
    pyautogui.moveTo(961,531)


Solution 1:[1]

This should work :)

!pip install keyboard
import keyboard

while True:
    # do your stuff
    if keyboard.read_key() != "":
        break

#continu here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ren