Python has a keyboard module with many features. Install it, perhaps with this command:

pip3 install keyboard

Then use it in code like:

import keyboard  # using module keyboard
while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        if keyboard.is_pressed('q'):  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
    except:
        break  # if user pressed a key other than the given key the loop will break
Answer from user8167727 on Stack Overflow
๐ŸŒ
PythonForBeginners.com
pythonforbeginners.com โ€บ home โ€บ how to detect keypress in python
How to Detect Keypress in Python - PythonForBeginners.com
June 30, 2023 - To detect the keypress in Python, we will use the is_pressed() function defined in the keyboard module. The is_pressed() takes a character as input and returns True if the key with the same character is pressed on the keyboard.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ how-to-detect-if-a-specific-key-pressed-using-python
How to detect if a specific key pressed using Python? - GeeksforGeeks
July 23, 2025 - Example 2: Here you can detect a specific key is being been pressed or not. ... from pynput.keyboard import Key, Listener def show(key): if key == Key.tab: print("good") if key != Key.tab: print("try again") # by pressing 'delete' button # you can terminate the loop if key == Key.delete: return False # Collect all event until released with Listener(on_press = show) as listener: listener.join() ... Here we are taking an input from a user and detecting that the user has entered the specified Alphanumerical(characters representing the numbers 0 - 9, the letters A - Z (both uppercase and lowercase), and some common symbols such as @ # * and &.) or not.
Discussions

How to detect a keypress when the program is running?
There is no simple way of doing it https://stackoverflow.com/questions/24072790/how-to-detect-key-presses More on reddit.com
๐ŸŒ r/learnpython
6
4
October 1, 2021
python - How can I check for a key press at any point during a loop? - Stack Overflow
I am trying to make a timer that counts down to 0, then starts counting up. I am using the time and keyboard modules. The keyboard module from PyPi. Everything works as expected, and I am able to ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to kill a while loop with a keystroke? - Stack Overflow
I am reading serial data and writing to a csv file using a while loop. I want the user to be able to kill the while loop once they feel they have collected enough data. while True: #do a bunch... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to break this loop in Python by detecting key press - Stack Overflow
Anyway, these methods can only ... the loop by pressing any buttons. By the way, as you see, my code aims to record the video again and again until I press a button. Is that possible to stop recording immediately after pressing? 2014-03-04T23:51:59.417Z+00:00 ... @VaFancy you can get any keypress by putting ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 22, 2017
Top answer
1 of 16
144

Python has a keyboard module with many features. Install it, perhaps with this command:

pip3 install keyboard

Then use it in code like:

import keyboard  # using module keyboard
while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        if keyboard.is_pressed('q'):  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
    except:
        break  # if user pressed a key other than the given key the loop will break
2 of 16
114

For those who are on windows and were struggling to find an working answer here's mine: pynput.

Here is the pynput official "Monitoring the keyboard" source code example:

from pynput.keyboard import Key, Listener

def on_press(key):
    print('{0} pressed'.format(
        key))

def on_release(key):
    print('{0} release'.format(
        key))
    if key == Key.esc:
        # Stop listener
        return False

# Collect events until released
with Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

The function above will print whichever key you are pressing plus start an action as you release the 'esc' key. The keyboard documentation is here for a more variated usage.

Markus von Broady highlighted a potential issue that is: This answer doesn't require you being in the current window to this script be activated, a solution to windows would be:

from win32gui import GetWindowText, GetForegroundWindow
current_window = (GetWindowText(GetForegroundWindow()))
desired_window_name = "Stopwatch" #Whatever the name of your window should be

#Infinite loops are dangerous.
while True: #Don't rely on this line of code too much and make sure to adapt this to your project.
    if current_window == desired_window_name:

        with Listener(
            on_press=on_press,
            on_release=on_release) as listener:
            listener.join()
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to detect a keypress when the program is running?
r/learnpython on Reddit: How to detect a keypress when the program is running?
October 1, 2021 -

I have a program which takes user input and outputs an answer. Now, I'd like to make it so that when the user presses a certain key, it exits the program. But how can you make it so that the program tries to detect that exit keypress at all times? Even when its looking for a user input?

I am only able to do one step at a time, like user input/output, then exit, or I can put exit first but that will just exit before anything happens

Thanks in advance!

๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ python detect keypress
How to Detect Keypress in Python | Delft Stack
February 12, 2024 - The function detect_keypress is defined to continuously detect and respond to keypress events. It prompts the user to press any key, entering a loop that waits for a keypress. The readchar.readkey() function captures a single keypress and stores ...
Top answer
1 of 2
1

Using callback is common approach in such case, here is solution:

import time
import keyboard

m = 2
s = 0
count_down = True

break_loop_flag = False

def handle_q_button():
    print('q pressed')
    global break_loop_flag
    break_loop_flag = True

keyboard.add_hotkey('q', handle_q_button)

while True:
    if break_loop_flag:
        break
    print(f"{m} minutes, {s} seconds")
    if count_down:
        if s == 0:
            m -= 1q
            s = 60
        s -= 1
    elif not count_down:
        s += 1
        if s == 60:
            m += 1
            s = 0
    if m == 0 and s == 0:
        count_down = False
    time.sleep(1)
2 of 2
1

If you want to do any two things in parallel, independently of another, you need to consider using multiprocessing. However, even if you do, your loop will either still need to check if a key has been registered in the other process, or you need to terminate the process running the loop forcefully, which may result in unexpected outcomes.

However, in your case, since there are no side effects like files being written, this would work:

import time
import keyboard
from multiprocessing import Process


def print_loop():
    m = 2
    s = 0
    count_down = True

    while True:
        print(f"{m} minutes, {s} seconds")
        if count_down:
            if s == 0:
                m -= 1
                s = 60
            s -= 1
        elif not count_down:
            s += 1
            if s == 60:
                m += 1
                s = 0
        if m == 0 and s == 0:
            count_down = False
        time.sleep(1)


def main():
    p = Process(target=print_loop)
    p.start()
    # this loop runs truly in parallel with the print loop, constantly checking
    while True:
        if keyboard.is_pressed('q'):
            break
    # force the print loop to stop immediately, without finishing the current iteration
    p.kill()


if __name__ == '__main__':
    main()
๐ŸŒ
Raspberry Pi Forums
forums.raspberrypi.com โ€บ board index โ€บ programming โ€บ python
Detect keypress in Python in a simple way? - Raspberry Pi Forums
Can someone please explain to me a simple way of detecting key presses in python without using root or the pygame library? ... from tkinter import * def keydown(e): print( e.char ) root = Tk() frame = Frame(root, width=100, height=100) lbl = Label(frame, text="Press a key") lbl.pack() frame.bind("<KeyPress>", keydown) frame.pack() frame.focus_set() root.mainloop() This displays a window which waits for keypresses, and displays the key pressed on the console.
๐ŸŒ
Medium
medium.com โ€บ @dinali_peiris โ€บ python-key-board-input-detection-985c253e7aaf
Python โ€” Key Board Input Detection - Dinali Peiris - Medium
September 17, 2023 - Letโ€™s see how we can detect key ... character is pressed on the keyboard . therefore, we can use the is_pressed() function with a while loop to detect keypress ....
Find elsewhere
๐ŸŒ
Java2Blog
java2blog.com โ€บ home โ€บ python โ€บ detect keypress in python
Detect keypress in Python - Java2Blog
June 12, 2021 - The break statement will come out of this code block. If it is removed, then the code will keep on executing. Thatโ€™s all about how to detect keypress in Python.
๐ŸŒ
IQCode
iqcode.com โ€บ code โ€บ python โ€บ detect-key-press-python
detect key press python Code Example
September 16, 2021 - d detect what key is pressed python detect what key is pressed pythn get all presses python python if space pressed key press read in python python get keystroke python keyboard check if a key is not pressed python keydown check check if hotkey pressed python pyqt detect key press anywhere how to get keydown once python python keyboard doesn't register keypress python register key press in game if space is pressed python register event listener in python for keypress event handler in python for key press python 3 check shell key press python detect keyboard click get key pressed python 3 get k
๐ŸŒ
CopyProgramming
copyprogramming.com โ€บ howto โ€บ how-to-check-if-a-key-is-pressed-during-a-loop-python
Python: Python: Detecting Keypress Within Loop - A Guide
May 1, 2023 - import pygame as py import time sc = py.display.set_mode((800, 600)) x = 350 y = 300 blue = (0, 0, 255) last = 0 def move(times, yspeed, xspeed): for i in range(times): global x, y x += (xspeed / times) y += (yspeed / times) time.sleep((xspeed / times / 10) + (yspeed / times / 10)) while True: key = py.key.get_pressed() for event in py.event.get(): if event.type == py.KEYDOWN: last = event.key else: last = 0 if event.key == py.K_UP and event.key == py.K_l: y -= 0.1 sc.fill((0,255,0)) py.draw.rect(sc, blue, (x,y,50,50)) py.display.flip() Python-Turtle - Moving the turtle by holding down a key: releasing, Edit: oh, it's the setheading() function being repeated that causes the hangup.
๐ŸŒ
Nitratine
nitratine.net โ€บ blog โ€บ post โ€บ how-to-detect-key-presses-in-python
How to Detect Key Presses In Python - Nitratine
April 7, 2020 - This demonstration shows you how to detect key presses using the pynput module. These can then be logged to a file as no console is displayed. This is very similar to a key logger.
๐ŸŒ
CodePal
codepal.ai โ€บ code generator โ€บ python loop until key press
Python Loop Until Key Press - CodePal
November 5, 2024 - Learn how to create a Python function that runs a loop until a specific key is pressed, enhancing user interaction in your applications.
๐ŸŒ
CopyProgramming
copyprogramming.com โ€บ howto โ€บ python-how-to-detect-a-keypress-with-python
Python: Detecting Keypresses in Python: A How-To Guide
March 26, 2023 - The module's 'print()' function is then used to display the message "Key Pressed" along with the key pressed by the user, denoted by 'k'. The 'break' statement is then used to exit the loop. This function from the module is commonly used to read user input for key presses.
๐ŸŒ
CodePal
codepal.ai โ€บ code generator โ€บ python key press loop function
Python Key Press Loop Function - CodePal
July 28, 2024 - To implement this functionality, we will use the keyboard module in Python. This library allows us to detect keyboard events easily. To install the keyboard module, you can use pip: ... Make sure you have the necessary permissions to run scripts ...