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
๐ŸŒ
Raspberry Pi Forums
forums.raspberrypi.com โ€บ board index โ€บ programming โ€บ python
Detect keypress in Python in a simple way? - Raspberry Pi Forums
I actually encountered this exact ... headless so had to fire the script off from SSH. You will need to wrap the keyboard checks in a "try: <code> except: pass" to prevent the errors in an SSH shell....
๐ŸŒ
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 ...
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
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
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
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
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!

๐ŸŒ
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. is_pressed() will take a character as input and return True if the ...
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ keyboard
keyboard ยท PyPI
import keyboard keyboard.press_and_release('shift+s, space') keyboard.write('The quick brown fox jumps over the lazy dog.') keyboard.add_hotkey('ctrl+shift+a', print, args=('triggered', 'hotkey')) # Press PAGE UP then PAGE DOWN to type "foobar". keyboard.add_hotkey('page up, page down', lambda: keyboard.write('foobar')) # Blocks until you press esc. keyboard.wait('esc') # Record events until 'esc' is pressed. recorded = keyboard.record(until='esc') # Then replay back at three times the speed. keyboard.play(recorded, speed_factor=3) # Type @@ then press space to replace with abbreviation. keyboard.add_abbreviation('@@', 'my.long.email@example.com') # Block forever, like `while True`. keyboard.wait() Events generated under Windows don't report device id (event.device == None). #21 ยท Media keys on Linux may appear nameless (scan-code only) or not at all.
      ยป pip install keyboard
    
Published ย  Mar 23, 2020
Version ย  0.13.5
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ python detect keypress
How to Detect Keypress in Python | Delft Stack
February 12, 2024 - The keyboard.Listener is used as a context manager that starts the listening process. The listener.join() method is called to wait until the listener stops, which happens when the escape key is pressed. ... While there are multiple methods to capture key inputs in Python, the readchar library offers a simple and efficient way to detect single keypresses.
Find elsewhere
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.

๐ŸŒ
Read the Docs
pynput.readthedocs.io โ€บ en โ€บ latest โ€บ keyboard.html
Handling the keyboard โ€” pynput 1.7.6 documentation
A possible workaround is to just dispatch incoming messages to a queue, and let a separate thread handle them. If a callback handler raises an exception, the listener will be stopped. Since callbacks run in a dedicated thread, the exceptions will not automatically be reraised.
๐ŸŒ
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.
๐ŸŒ
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() ...
๐ŸŒ
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.
๐ŸŒ
Java2Blog
java2blog.com โ€บ home โ€บ python โ€บ detect keypress in python
Detect keypress in Python - Java2Blog
June 12, 2021 - We can also use the is_pressed() function to check whether a specific key is pressed or not. It will return a True or False value. ... The on_press_key() function can execute a function when a specific key is pressed.
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-17568.html
Keypress when running a python app in a console on windows
April 16, 2019 - Hi all, I have a small python program running for the windows command window (console app) I want to detect a keypress when the console app has not got focus. I tried several ways to do this but it never seems to work. Steve
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 56502260 โ€บ detect-keypress-but-only-once-keyboard-module-isnt-working-this-way
python - Detect keypress but only once. Keyboard module isn't working this way - Stack Overflow
#main waitingForA = True while True: wn.update() if keyboard.is_pressed('a') and waitingForA: # <- count_a -= 1 pen.clear() pen.write(count_a, align="center", font=("courier", 24, "normal")) waitingForA = False # <- Notice how I added the waitForA variabiel, then set it to False after we got our first press, this will then stop the if statement from running a second time since our if statement resolves to True and False, which obviously won't run in an and statement.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 51140188 โ€บ detect-key-pressed-in-python-not-working
keyboard - Detect key pressed in python not working - Stack Overflow
July 2, 2018 - from pynput import keyboard import pyautogui import threading import sys class Status: _exit = False active = True names = [str(i) for i in range(0, 10, 1)] width, height = pyautogui.size() def mainThread(): listenerThread = keyboard.Listener(on_press = onKeyPress) listenerThread.start() while(not Status._exit): if (not Status.active): continue pyautogui.click(90, height - 110) for i in range(len(names)): if (not Status.active or Status._exit): break pyautogui.typewrite(names[i]) pyautogui.press("enter") keyboard.Listener.stop(listenerThread) print("Stopped listerning") sys.exit(0) def onKeyPress(key): print("Still listerning") try: k = key.char except Exception: k = key.name if (k == "z"): Status.active = not Status.active elif (k == "x"): Status._exit = not Status._exit #controlThread = threading.Thread(target = mainThread) #controlThread.start() mainThread()