Exiting infinite loop with keypress in python

Jul 26, 2022
Reaction score
Hello, I want my python script to perform left clicks until I tell it to stop with a key press. I have successfully created some infinite loops but I cannot get python to stop with a key press.

I am using the following modules:
pyautogui (for the actions I want automated and looped)
keyboard (I am experimenting with additional steps in my code, like keyboard.wait so I can control with a key press when I want my loop to start)
sys ( I have tried to use sys.exit() and sys.quit() to exit my loop\

Try1 - opens and clicks but pressing the hotkey has no effect. I thought to put the add_hotkey above pyautogui.click which I did in Try2
Try2 - opens but kills the script without any clicks happening
Try3 - trying sys.quit with lambda: but pressing the hotkey has no effect.
Try4 - I tried to bind adding count to a hotkey in order to satisfy the condition, the loop runs but pressing the hotkey has no effect
Try5 - I tried a different approach as shown in the attachment, the script opens, performs 1 click and remains idle until hotkey is pressed, it closes once hotkey is pressed

Can someone help me to understand where I'm going wrong?


  • Try 1.PNG
    Try 1.PNG
    12.8 KB · Views: 7
  • Try3.PNG
    11.6 KB · Views: 8
  • Try2.PNG
    12.5 KB · Views: 7
  • Try4.PNG
    15.4 KB · Views: 5
  • Try5.PNG
    12.8 KB · Views: 8


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question