Search code examples
pythonpyautogui

Stop my code when pressing keyboard button


my problem is when i press "p" code not stopping. I have to spam "p" for stopping code, probably there is time.sleep and i have to wait for it but i cant wait for it. I want to stop code immediately when i press p. is there any way for it ? there is my code

import pyautogui as pg
import keyboard
import time
from PIL import Image

button = "p"

def m():
    if pg.locateOnScreen('Screenshot_2.png', confidence = 0.9):
        pc = pg.locateOnScreen('Screenshot_2.png', confidence = 0.9)
        pg.center(pc)
        pg.click(pc)
        print('found!')
        time.sleep(2)
    else:
        time.sleep(3)
        print('not found!')
        
        
while True:
    m()
    if keyboard.is_pressed(button):
        print("stopped")
        break

Solution

  • Because it's checking if the key is pressed in the exact moment that if statement is executed. Which is a problem when that loop is spinning so fast. You can use a callback to essentially cache the should stop condition.

    import pyautogui as pg
    import keyboard
    import time
    from PIL import Image
    
    button = "p"
    
    stop = False
    def onkeypress(event):
        global stop
        if event.name == button:
            stop = True
    
    def m():
        if pg.locateOnScreen('Screenshot_2.png', confidence = 0.9):
            pc = pg.locateOnScreen('Screenshot_2.png', confidence = 0.9)
            pg.center(pc)
            pg.click(pc)
            print('found!')
            time.sleep(2)
        else:
            time.sleep(3)
            print('not found!')
            
          
    keyboard.on_press(onkeypress)  
    while True:
        m()
        if stop:
            print("stopped")
            break