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
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!

๐ŸŒ
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 1: Here you will see which key is being pressed. ... from pynput.keyboard import Key, Listener def show(key): print('\nYou Entered {0}'.format( key)) if key == Key.delete: # Stop listener return False # Collect all event until released with Listener(on_press = show) as listener: listener.join()
๐ŸŒ
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 ...
๐ŸŒ
Raspberry Pi Forums
forums.raspberrypi.com โ€บ board index โ€บ programming โ€บ python
Detect keypress in Python in a simple way? - Raspberry Pi Forums
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. ... The keyboard library does indeed require sudo permissions. From their "Known Limitations" list: To avoid depending on X, the Linux parts reads raw device files (/dev/input/input*) but this requires root. Also, due to no HID devices being loaded in an SSH session, keyboard library will indeed throw the non-descript error.
๐ŸŒ
Quora
quora.com โ€บ How-do-you-check-if-a-key-was-pressed-in-Python-Python-Python-3-x-development
How to check if a key was pressed in Python (Python, Python 3.x, development) - Quora
Answer (1 of 2): Oof, this is one of those topics that hits close to home, as I recently wrote a script that needed to read keypresses, and had a hell of a time at it. The biggest problem is thereโ€™s no standard library for doing this in every operating system.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to detect keypress in python? without wait the user to press any key
r/learnpython on Reddit: How to detect keypress in Python? Without wait the user to press any key
May 23, 2020 -

I need to detect if any key is pressed but i cannot wait until the user press anything

Like he only gonna press any key if he wants to stop the program,so the program need to continue while he dont press nothing

Ps:sorry my bad english

from datetime import datetime
import os
from msvcrt import getch
from time import sleep

def get_down(time):
    print('press ENTER to cancel \n')
    while True:
        key = ord(getch())    #the program stop wanting the user to press a key
        if key == 13:
            print('You cancel the operation')
            break

        if time == hours:
            print("The system is gonna turn off")
            sleep(5)
            os.system("shutdown /s /t 1")


hours = datetime.now().strftime('%H:%M')
print('Now is: {}'.format(hours))
get_down(str(input('When you want to shutdown? (hh:mm):')))
๐ŸŒ
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 ... this scenario iโ€™m going to use keypress in python . we will use is_pressed() function defined in the keyboard module. is_pressed() will take a character as input and return True if the key ...
Find elsewhere
๐ŸŒ
YouTube
youtube.com โ€บ watch
How to Detect Key Presses with Python - YouTube
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
Published ย  April 29, 2021
๐ŸŒ
Nitratine
nitratine.net โ€บ blog โ€บ post โ€บ how-to-detect-key-presses-in-python
How to Detect Key Presses In Python - Nitratine
April 7, 2020 - def on_press(key): print("Key pressed: {0}".format(key)) def on_release(key): print("Key released: {0}".format(key)) If you want this script to be run in the background. Click File -> Save As and save it with a .pyw file extension.
๐ŸŒ
Java2Blog
java2blog.com โ€บ home โ€บ python โ€บ detect keypress in python
Detect keypress in Python - Java2Blog
June 12, 2021 - The wait() function waits for the user to press some specific key and then resume the program execution. ... We can also use the is_pressed() function to check whether a specific key is pressed or not.
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ python detect keypress
How to Detect Keypress in Python | Delft Stack
February 12, 2024 - The listener.join() method is called ... multiple methods to capture key inputs in Python, the readchar library offers a simple and efficient way to detect single keypresses....
๐ŸŒ
Snap! Forum
forum.snap.berkeley.edu โ€บ computer science
How do you detect key presses in python? - Computer Science - Snap! Forum
September 25, 2020 - I have tried to make a script in python that detects key presses, but imports such as Tkinter and keyboard aren't recognised. Can anybody help? Thanks!
๐ŸŒ
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 - This module provides a simple and efficient way to listen for keyboard events in your Python programs. To wait for a keypress, you simply need to create an instance of the `keyboard.Listener` class and define a callback function that will be called every time a key is pressed or released. This function should then check whether the key pressed is the one you are waiting for, and if so, perform the desired action.
๐ŸŒ
Rosetta Code
rosettacode.org โ€บ wiki โ€บ Keyboard_input โ€บ Keypress_check
Keyboard input/Keypress check - Rosetta Code
February 20, 2026 - Returns a character string if a key is pressed during the call of Inkey(). It doesn't interrupt (halt) the program flow. If special keys (non-ASCII) have to be handled, RawKey() should be called after Inkey(). ... #!/usr/bin/env python # -*- ...
๐ŸŒ
Tech-Artists.Org
tech-artists.org โ€บ coding
Detecting a key press during command execution - Coding - Tech-Artists.Org
February 7, 2024 - I am trying to detect a key press in the middle of command execution in Python Maya. I first tried a brute-force approach using the QApplication event queue (probably not the optimal way): class MyEventHandler(QtCore.QObject): def eventFilter(self, qobj, event): if event.type() == QtCore.QEvent.KeyPress: print('key pressed') return super(MyEventHandler, self).eventFilter(qobj, event) class MyCmd(OpenMayaMPx.MPxCommand): def __init__(self): super(...