How do you make python end a loop with a press of a key while tabbed out and in a loop constantly pressing left click and right click?

Viewed 33

I am relatively new to python and coding in general. I've created a script to help me perform a repetitive task. My script is perfectly fine, except the part where I literally can't find a way to kill it. My script constantly presses the left and right mouse buttons and I would like a solution to kill it while tabbed out in another tab. I've tried if keyboard.is_pressed('e') break with importing pynput and using the right code (I couldn't really figure out format code well on this website). What solutions can I use? My script as of now is:

while True:
    mouse.click(Button.right)
    enter code here
    time.sleep(0.90)
    mouse.click(Button.left)
1 Answers

When the key is pressed the break statement will trigger and the while loop will terminate. If the key is not pressed the sequence will be repeated.

while true:
    mouse.click(Button.right)
    # enter code here
    time.sleep(0.90)
    mouse.click(Button.left)
    def on_press(key):
    break

with Listener(
    on_press=on_press,
    on_release=on_release) as listener:
    listener.join()
Related