The easiest way is to just interrupt it with the usual Ctrl-C (SIGINT).

try:
    while True:
        do_something()
except KeyboardInterrupt:
    pass

Since Ctrl-C causes KeyboardInterrupt to be raised, just catch it outside the loop and ignore it.

Answer from Keith on Stack Overflow
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how do i loop my code and stop it with one key press?
r/learnpython on Reddit: How do i loop my code and stop it with one key press?
December 21, 2021 -

Hey everyone!,

atm i need to repeat some code but i am not to sure how, i think i have to use while loops. And i need it to repeat an infinite amout of times untill i press a button for instance "q"

import time
import pyautogui
import pydirectinput
import time

<While loop?>

time.sleep(5)
pydirectinput.keyDown('d')
time.sleep(3)
pydirectinput.keyUp('d')
time.sleep(31)
pydirectinput.leftClick(982, 876)

<If statment where i need to press q to stop the sript?>

Thank you to anyone who can help me :)

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ how-to-kill-a-while-loop-with-a-keystroke-in-python
How to Kill a While Loop with a Keystroke in Python? - GeeksforGeeks
July 23, 2025 - This article covers three simple ways to break a while loop using a keystroke: ... This method allows you to manually stop the loop by pressing Ctrl+C.
๐ŸŒ
YouTube
youtube.com โ€บ logicgpt
how to stop while loop in python with key press - YouTube
Download this code from https://codegive.com Certainly! In Python, you can use the keyboard library to detect keypress events and then use this to control th...
Published ย  January 19, 2024
Views ย  246
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Python while Loop (Infinite Loop, break, continue) | note.nkmk.me
August 18, 2023 - To stop the infinite loop using keyboard interrupt instead of setting break, you can catch the KeyboardInterrupt. try: while True: time.sleep(1) print('processing...') except KeyboardInterrupt: print('!!FINISH!!') ... If you press ctrl + c in the ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ terminating a while loop when a certain key is pressed
r/learnpython on Reddit: Terminating a while loop when a certain key is pressed
December 8, 2022 -

How would you terminate this while loop, if let's say the key 'c' is pressed? So far my research has led me to a keyboard interrupt exception but I'm not sure if that is what I want.

x = True
while x:
    print("While loop is on...")
    
    if any key is pressed: <--- LET'S SAY THE KEY 'C' IS PRESSED, HOW CAN I TERMINATE THE LOOP?
        x = False
        print("While loop is off...")
๐ŸŒ
Finxter
blog.finxter.com โ€บ home โ€บ learn python blog โ€บ how to kill a while loop with a keystroke in python?
How to Kill a While Loop with a Keystroke in Python? - Be on the Right Side of Change
June 9, 2022 - To end a while loop prematurely in Python, press CTRL-C while your program is stuck in the loop. This will raise a KeyboardInterrupt error that terminates the whole program. To avoid termination, enclose the while loop in a try/except block ...
๐ŸŒ
McNeel Forum
discourse.mcneel.com โ€บ scripting
Please help me to exit While Loop in python when I press the enter key - Scripting - McNeel Forum
February 16, 2021 - I want to know how to exit While Loop when I press the enter key. I want to do a specific action until I press Enter. Please give me a simple example. The code I tested. import rhinoscriptsyntax as rs while True: rs.Command(โ€™_circleโ€™) n = input('enter : ') if n == โ€˜โ€™: break;
Find elsewhere
๐ŸŒ
YouTube
youtube.com โ€บ codestack
python exit while loop with keypress - YouTube
Download this code from https://codegive.com Title: Python Exit While Loop with Keypress: A Step-by-Step TutorialIntroduction:In this tutorial, we will explo...
Published ย  December 28, 2023
Views ย  81
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to stop a while loop by inputting a keypress
r/learnpython on Reddit: How to stop a while loop by inputting a keypress
May 23, 2022 -

I'm trying to create an autoclicker using the pyautogui library. I want to create a fail safe for the user to break out of the auto clicker in case the cursor is not able to be moved and the user can't stop the program. I'm using the keyboard library to implement a hotkey to stop the auto clicker from running, but I'm not getting the intended behavior. The click() function is only executed once and the program quits. I'm on a Arch Linux, and gave the program root privileges as mentioned in the readme of keyboard. I've tried other variations under the Invoking code when an event happens of the readme, but none of them worked.

def repeat_until_stop():     
    while True:
        pyautogui.click()
        event = keyboard.read_event()
        if event.event_type == keyboard.KEY_DOWN and event.name == 'q':
            break
๐ŸŒ
The Coding Forums
thecodingforums.com โ€บ programming languages โ€บ python
Breaking infinite loop with key stroke | Python | Coding Forums
July 26, 2022 - Then I switched my approach and tried making an infinite while loop that runs when the count is above 0 and making a hotkey that makes the count equal to 0 thus, breaking the loop in my understanding (Try4). In my last attempt I tried to bind break to a hotkey and if the hotkey is not pressed, make my script do a leftclick (Try5).
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 72341295 โ€บ how-to-stop-while-loop-when-key-pressed
python - How to stop while loop when key pressed - Stack Overflow
I want it to stop at any time you click s, not if you click s every 1 second. Can someone help me do this? ... Sleep shorter, but only print the time each time the time changes, or you can use the on_key_press event that supports a callback that you could use to change the current state: github.com/boppreh/keyboard#keyboard.on_press_key
๐ŸŒ
YouTube
youtube.com โ€บ how to fix your computer
PYTHON : How to kill a while loop with a keystroke? - YouTube
PYTHON : How to kill a while loop with a keystroke? [ Gift : Animated Search Engine : https://www.hows.tech/p/recommended.html ] PYTHON : How to kill a whil...
Published ย  December 6, 2021
Views ย  176
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how do i exit a while loop from a keypress without using keyboardinterrupt? [python]
r/learnpython on Reddit: How do I exit a while loop from a keypress without using KeyboardInterrupt? [python]
July 10, 2020 -

I am making a timer that beeps every x seconds but the timer restarts during a certain keypress. The first part of the code gets the timer to start. Then it goes into a while loop for the timer. I want to interrupt the loop without pressing keyboard interrupt but rather another key.

Any help?Here is the code below

import time, winsound, keyboard

x = 0
while x == 0:
    if keyboard.is_pressed(','):
        x = x+1
while True:
    try:
        while x==1:
            for i in range(29):
                time.sleep(1)
                print(i)
                if i == 28:
                    winsound.Beep(300,250)
    except KeyboardInterrupt: 
            continue
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 73732358 โ€บ none-stop-while-loop-responsive-to-user-key-press
python - none stop while loop responsive to user key press - Stack Overflow
terminedia is one such 3rdy party project - among other niceties, it implements the inkey() call which is similar to old-time BASIC function with the same name: it returns the key currently pressed, if there is one, or an empty string. You just have to call it inside a context block using the terminedia keyboard: with terminedia.keyboard: So, you have to first install terminedia in your Python environment with pip install terminedia. Then your code could be like this: import terminedia as TM n = 1 with TM.keyboard: while True: # do something n += 1 if (pressed:=TM.inkey()) == "p": # do task 1 if pressed == "f": # exit while break
๐ŸŒ
Forum
forum.cogsci.nl โ€บ discussion โ€บ 1258 โ€บ solved-breaking-a-loop-by-key-press-how-do-i-do-that
[solved] Breaking a loop by key press? How do I do that? โ€” Forum
November 30, 2014 - What you can do is defining a variable that is True if you want to run a loop and False if not. Then you only have to monitor your keypresses and set the variable to Falseas soon as space is pressed.