How to make my loop start and stop with key presses in python?

Viewed 39

My code will start (pressing p) and stop (pressing o) the loop once, but won't start the loop again, what am I doing wrong?

import pyautogui, time, keyboard

while True:
    if keyboard.is_pressed('p'):
        print("Rodando")
        x=0
        while True:
            if x == 0:
                pyautogui.press("F7")
                pyautogui.press("F7")
                print("a")
                time.sleep(0.1)
                pyautogui.press("F7")
                pyautogui.press("F7")
                print("b")
                time.sleep(0.5)
                if keyboard.is_pressed('o'):
                    print("abortando")
                    x = 1
1 Answers

Try this code.

import pyautogui, time, keyboard
A = False
def start_loop():
    global A
    while True:
        if keyboard.is_pressed('p') or A:
            print("Rodando")
            A = True
            x=0
            while True:
                if x == 0:
                    pyautogui.press("F7")
                    pyautogui.press("F7")
                    print("a")
                    time.sleep(0.1)
                    pyautogui.press("F7")
                    pyautogui.press("F7")
                    print("b")
                    time.sleep(0.5)
                    if keyboard.is_pressed('o'):
                        print("abortando")
                        x = 1
                        A = False
                        break
    start_loop()

start_loop()

keyboard module does not always work if this happens then please press the key again.

Related