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()
🌐
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 - 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() ...
Discussions

How do you detect key presses in python? - Computer Science - Snap! Forum
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! More on forum.snap.berkeley.edu
🌐 forum.snap.berkeley.edu
0
September 25, 2020
How to detect keypress in python using keyboard module? - Stack Overflow
I am making a program in python to detect what key is pressed and based on my keyboard it will make a decision. I want to implement it using keyboard module in python. I would do something like th... More on stackoverflow.com
🌐 stackoverflow.com
Can I detect a key press from an external keyboard?
I don't have a definitive answer for you but I believe the answer less in the device_id. You need to identify the exact device id and limit your captures to that. On the keyboard module documentation the dev says that there is a known issue in Windows implementation is that it doesn't report the device id. I'm not sure if you're system is linux or windows. More on reddit.com
🌐 r/learnpython
15
1
June 13, 2023
How do I use the Python keyboard module to detect a key press? - Stack Overflow
I am working on a self challenge of making a cash register in Python, and I'm looking to use the keyboard module for inputting values instead of typing them into the console. However, I think the More on stackoverflow.com
🌐 stackoverflow.com
🌐
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!

🌐
PythonForBeginners.com
pythonforbeginners.com › home › how to detect keypress in python
How to Detect Keypress in Python - PythonForBeginners.com
June 30, 2023 - Instead of the is_pressed() function, we can use the read_key() function to detect the keypress in Python. The read_key() function returns the key pressed by the user. We can use the read_key() function with a while loop to check whether the ...
🌐
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. ... The keyboard library does indeed require sudo permissions.
🌐
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 ... in this scenario i’m going to use keypress in python . we will use is_pressed() function defined in the keyboard module....
🌐
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....
Find elsewhere
🌐
Java2Blog
java2blog.com › home › python › detect keypress in python
Detect keypress in Python - Java2Blog
June 12, 2021 - To detect keypress, we can use a few functions from this module. The read_key() function from this module is used to read the key pressed by the user. We can check whether the pressed key matches our specified key.
🌐
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!
🌐
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.
🌐
PyPI
pypi.org › project › keyboard
keyboard · PyPI
Listen and send keyboard events. Works with Windows and Linux (requires sudo), with experimental OS X support (thanks @glitchassassin!). Pure Python, no C modules to be compiled.
      » pip install keyboard
    
Published   Mar 23, 2020
Version   0.13.5
🌐
YouTube
youtube.com › watch
Python Detect Keypress | Python Detect Keyboard Input Easiest Way! - YouTube
Subscribe✔http://bit.ly/Sub2CoderGautam Hello Guys, welcome back to Coder Gautam. In this video, I am going to show you How to Detect Keyboard Input Easiest...
Published   June 21, 2020
🌐
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.
Top answer
1 of 3
1

There are usually many different ways to code something. Some are better than others. In a problem that is based on keyboard input, like your cash register/adding machine project, I would go with an event-driven approach. Your sample code represents a polling approach. It can work, but it may not be as efficient.

I've never used the keyboard module before, but I did some quick research and came up with the below program, which may give you guidance. Every time a key in the keyboard is pressed, the key_pressed() routine is triggered. Digits are stored, and the Enter key causes an addition and then clearing of the stored digits.

    import keyboard

    sin = ""
    val = 0.0

    def key_pressed(e, *a, **kw):
            global sin, val
            
            # print(e, a, kw)
            k = e.name
            if k in "0123456789":
                    sin += k
            elif k == 'enter':
                    val += float(sin)/100.0
                    print("Entered: " + sin)
                    print('Value: ', val)
                    sin = ""
    keyboard.on_press(key_pressed)
2 of 3
0

I took a look at the documentation located here https://github.com/boppreh/keyboard.

I ran and tested this code on python 3.9

import keyboard
from functools import partial 

num = ""

def add(i):
    global num
    num += str(i)
    print(num, end='\r')

for i in range(10): # numbers 0...9
    keyboard.add_hotkey(str(i), partial(add, i)) # add hotkeys

keyboard.wait('enter') # block process until "ENTER" is pressed

print("\nNum:{}".format(num))

You could additionally unhook the hotkeys by calling keyboard.unhook_all_hotkeys() after grabbing the number. I imagine you could wait on "+" and "-" if you wanted to implement addition and subtraction of numbers.

🌐
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
🌐
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 - One way to wait for a keypress in Python is by using the `getch()` function from the `keyboard` module. The `getch()` function waits for a single keypress and returns the character representation of the key that was pressed.
🌐
Jon Witts' Blog
jonwitts.co.uk › archives › 896
Detecting keyboard input in Python | Jon Witts' Blog
November 9, 2016 - #!/usr/bin/python3 # adapted from https://github.com/recantha/EduKit3-RC-Keyboard/blob/master/rc_keyboard.py import sys, termios, tty, os, time def getch(): fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch button_delay = 0.2 while True: char = getch() if (char == "p"): print("Stop!") exit(0) if (char == "a"): print("Left pressed") time.sleep(button_delay) elif (char == "d"): print("Right pressed") time.sleep(button_delay) elif (char == "w"): print("Up pressed") time.sleep(button_delay) elif (char == "s"): print("Down pressed") time.sleep(button_delay) elif (char == "1"): print("Number 1 pressed") time.sleep(button_delay)