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
๐ŸŒ
Pierian Training
pieriantraining.com โ€บ home โ€บ how to wait for a keypress in python
How to Wait for a Keypress in Python - Pierian Training
April 28, 2023 - If you want to wait for a keypress in Python, you can use the `msvcrt` module. This module provides access to a number of functions in the Microsoft Visual C runtime library, including the ability to read a single character from the console.
Discussions

python - How do I wait for a pressed key? - Stack Overflow
How do I make my python script wait until the user presses any key? More on stackoverflow.com
๐ŸŒ stackoverflow.com
Exiting infinite loop with keypress in python
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... More on thecodingforums.com
๐ŸŒ thecodingforums.com
1
July 26, 2022
How so I wait for a keystroke?
Contrary to what has been answered so far it is actually super simple to do what you describe. If I have not misunderstood you, you basically want to create some sort of hotkey functionality. Basically execute some code whenever button x is pressed on the keyboard. You can utilize the module keyboard or alternatively pynput for that. Keep in mind that you may need to run the script with admin privileges. Below is a quick example that triggers a function when the spacebar is hit. import keyboard def hotkey_callback(): print("Space was pressed!") keyboard.add_hotkey('space', hotkey_callback) # Stops the program when you hit esc keyboard.wait('esc') More on reddit.com
๐ŸŒ r/learnpython
16
2
September 14, 2023
python - While statement checking for button press while accepting raw input - Raspberry Pi Stack Exchange
I have a while statement running and checking if my button (on a gpio) is pressed and once it is I print something. I would like to add some shell commands like exit, etc... How can i have the while More on raspberrypi.stackexchange.com
๐ŸŒ raspberrypi.stackexchange.com
January 29, 2016
๐ŸŒ
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 :)

๐ŸŒ
PythonForBeginners.com
pythonforbeginners.com โ€บ home โ€บ how to detect keypress in python
How to Detect Keypress in Python - PythonForBeginners.com
June 30, 2023 - Here, we have executed the while loop until the user presses the key โ€œaโ€. On pressing other keys, the is_pressed() function returns False , and the while loop keeps executing.
๐ŸŒ
The Coding Forums
thecodingforums.com โ€บ programming languages โ€บ python
Exiting infinite loop with keypress in python | Python | Coding Forums
July 26, 2022 - 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? ... Answered here - https://www.thecodingforums.com/threads/breaking-infinite-loop-with-key-stroke.973921/
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ make-python-wait-for-a-pressed-key
Make Python Wait For a Pressed Key - GeeksforGeeks
April 28, 2025 - Press any key to continue . . . The command, upon execution, stops the execution of the current thread and waits for a keypress. The keypress can be any key other than a modifier key (Ctrl, Shift, Alt, etc.). The following command, when integrated ...
Find elsewhere
๐ŸŒ
Linux Hint
linuxhint.com โ€บ python_pause_user_input
Python Pause For User Input โ€“ Linux Hint
If you want to wait for the user to press any key before terminating the script then you can call input() method with a message at the end of the script. The following script shows how you can pause the termination of the script and wait for the userโ€™s input.
๐ŸŒ
CodePal
codepal.ai โ€บ code generator โ€บ python loop until key press
Python Loop Until Key Press - CodePal
November 5, 2024 - To create a loop that runs until a specific key is pressed, we can use a while loop combined with the keyboard.is_pressed() function. This function checks if a particular key is currently being pressed.
๐ŸŒ
Network Direction
networkdirection.net โ€บ home โ€บ python โ€บ python resources โ€บ press enter to continue
Python - Press Enter to Continue
January 4, 2022 - The problem is that the Python window closes too quickly for you to tell. In a case like this, you want the script to pause before quitting. There are a few ways this could be done ยท A very simple option is just to wai a few seconds, and then continue on: import time print ('Waiting 5 seconds before continuing') time.sleep(5) If you want the script to wait until youโ€™re ready, you can ask for user input.
Top answer
1 of 2
3

Depending on how your circuit is wired you should use

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)

inputPin = "YOUR_PIN_GOES_HERE"
GPIO.setup(inputPin,GPIO.IN,pull_up_down=GPIO.PUD_UP)

def buttonPress(channel):
     #stuff

def buttonRelease(channel):
     #stuff


GPIO.add_event_detect(channel,GPIO.RISING,callback=buttonPress)
#OR
GPIO.add_event_detect(channel,GPIO.FALLING,callback=buttonRelease)

while(1):
      keypressed = raw_input('Press q to quit: ')
      if keypressed == 'q':
           break
      elif keypressed == 'SOME OTHER KEY':
           #code for some other thing
      else
           print("Unknown input")

These are events that will be trigged where there is a change on your input pin. Your raw_input can still handle whatver code you want because the event loop is running in the background.

Pulled from here

Edits: put the event defs above event declaration because I am teh dumb

While(1)'s are ugly. For the sake of staying a loop this should suffice though. Essentially this will run the keyboard input loop until you hit q. Use the elifs to handle other inputs. The else will capture unknown input and provide feedback. The break statment will boot the program out of the while loop and will reach the end of code and terminate.

Should you feel fancy and want to handle a lot of input I would look to use what other languages have a switch statement to clean up a bunch of elifs

Oh and standard warranty applies, I may have missed a tab or : here and there.

2 of 2
1

Your Python module will offer GPIO callbacks. Generally you specify

  • a GPIO
  • whether you are interested in rising edges (0->1), falling edges (1->0), or both edges
  • and a function to be called when the event happens

The specified function will be called asynchronously to the main thread, i.e. it will still be called even if the main thread is waiting in a raw_input.

Generally you would use global variables to pass state information between the callback and main thread.

๐ŸŒ
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 - Not that it matters, but it is a little unintuitive that your loop runs if breaking variable is True and breaks when it it False. ... Hi eduard, thank you. I think I understand, but when I change braking_variable (in the inline-scripts only) to var.breaking_variable I get the following error: AttributeError: response not found So I changed the duration of the sketchpad to 0 (instead of keypress) and included a keyboard_response-item.
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-29874.html
How to break a loop in this case?
I got this to work, but when I press s to stop the script, it will keep running the marketloop() function till end before stopping. My question is that how do I make the function stop instantly too? I tried adding break in stop buffing function but r...
๐ŸŒ
The Coding Forums
thecodingforums.com โ€บ programming languages โ€บ python
Breaking infinite loop with key stroke | Python | Coding Forums
July 26, 2022 - I used the following modules: pyautogui (for the actions I want my loop to perform) sys ( I tried binding sys.exit() and sys.quit() to a key) keyboard ( for controlling the loop with keyboard hotkeys) I tried binding sys.exit() to a hotkey within a while True loop (Try1+2), trying the same with lambda: (Try3). 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).
๐ŸŒ
CodeSpeedy
codespeedy.com โ€บ home โ€บ wait for key press in python
Wait for Key Press in Python - CodeSpeedy
January 18, 2024 - This is considered as an event. keyboard.on_press(on_key_event) # Check every 0.1 seconds if a key has been pressed for _ in range(int(timeout_duration * 10)): if key_pressed: print("Key pressed!") return True time.sleep(0.1) # Sleep for 0.1 ...
๐ŸŒ
DaniWeb
daniweb.com โ€บ programming โ€บ software-development โ€บ threads โ€บ 123777 โ€บ press-any-key-to-continue
python - Press Any Key to Continue | DaniWeb
import msvcrt def wait_any_key(prompt="Press any key to continue..."): print(prompt, end="", flush=True) while msvcrt.kbhit(): msvcrt.getch() # flush pending keys (e.g., prior Enter) msvcrt.getch() # now wait for a new key ... Use getwch() if you need Unicode key handling on Windows. curses is not available by default on Windows; if needed, install the Windows port via pip and test in a real console, not an IDE terminal. For background, see the Python docs for curses and msvcrt.