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 โ€บ generic use of keyboard.is_pressed(dict[key])
r/learnpython on Reddit: Generic use of keyboard.is_pressed(DICT[KEY])
August 17, 2022 -

I'm currently trying to make the use of the keyboard function keyboard.is_pressed() a bit more generic. Most use some line of code for each indivisual key, I would like to use the dictonary keys as possible input.

So I have a dict with different keyboard commands as keys and want it to react as soon as one of them is pressed. In my first try I didn't provide a particular key:

    import keyboard
    import time
    
    test = {'1': 'Test1', '2': 'Foo', '3': 'Bar'}
    
    while True:
        if keyboard.is_pressed('+'):
            time.sleep(1)
            while keyboard.is_pressed('-') != True:
                input = keyboard.is_pressed() #<- how can I use all Dict Keys here?

Which of course lead to the TypeError:

> is_pressed() missing 1 required positional argument: 'hotkey'.

I also tried `keyboard.is_pressed(test.keys())` which leads to

> TypeError: expected string or bytes-like object

Is there a way that I can use `keyboard.is_pressed()` with my dict keys or a list of possible keyboard keys?

Discussions

How does keyboard.is_pressed() work in Python? - Stack Overflow
Interesting reply. Does someone know where can I find a list of accepted key codes? I'm trying to make my script to react when F5 is pressed but it doesn't seem to recognize the 'f5' key. 2023-12-13T14:01:01.483Z+00:00 ... keyboard.is_pressed() is basically checking if a certain key code is pressed. More on stackoverflow.com
๐ŸŒ stackoverflow.com
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
pi 5 - module 'keyboard' has no attribute 'is_pressed' - I have trouble using pynput or keyboard libraries - Raspberry Pi 5 - Raspberry Pi Stack Exchange
Problem To use the pynput and keyboard libraries I have made a virtual environment and am executing my code using the sudo python command. I keep getting an error saying "An error occurred: module 'keyboard' has no attribute 'is_pressed'"; using the following code: More on raspberrypi.stackexchange.com
๐ŸŒ raspberrypi.stackexchange.com
August 6, 2024
Need help stopping an infinite loop with a key press
I would save the press command result into a Boolean and use while a_pressed = False as the loop control. In that case no need of break and we have a natural end of while. More on reddit.com
๐ŸŒ r/learnpython
18
0
December 28, 2022
๐ŸŒ
Medium
medium.com โ€บ @dinali_peiris โ€บ python-key-board-input-detection-985c253e7aaf
Python โ€” Key Board Input Detection - Dinali Peiris - Medium
September 17, 2023 - is_pressed() will take a character as input and return True if the key with the same character is pressed on the keyboard .
๐ŸŒ
Raspberry Pi Forums
forums.raspberrypi.com โ€บ board index โ€บ programming โ€บ python
Detect keypress in Python in a simple way? - Raspberry Pi Forums
My plan is to run a program on BrickPi3 using Python which is very simple - move the robot forward when pressing 'w', stop it when 's' is pressed. I'm new to BrickPi3 and this is just to test. I know this isn't the BrickPi forum, but the problem is about Python and actually doesn't have anything to do with Python. So this is my program: ... import brickpi3 from time import sleep import keyboard BP = brickpi3.BrickPi3() speed = 50 while True: if keyboard.is_pressed('w'): BP.set_motor_power(BP.PORT_B + BP.PORT_C, speed) if keyboard.is_pressed('s'): BP.set_motor_power(BP.PORT_B + BP.PORT_C, 0) My problem is that the keyboard module isn't working.
๐ŸŒ
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.
      ยป pip install keyboard
    
Published ย  Mar 23, 2020
Version ย  0.13.5
๐ŸŒ
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 - In this method, we will use pynput Python module to detecting any key press. "pynput.keyboard" contains classes for controlling and monitoring the keyboard. It Calls pynput.keyboard.Listener. stop from anywhere, or return False from a callback to stop the listener. This library allows you to control and monitor input devices. ... Create a with Statement: The with statement is used to wrap the execution of a block with methods defined by a context manager.
๐ŸŒ
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.
Find elsewhere
Top answer
1 of 2
1

I know that it was a year ago, but I have found this question today.

Sooo, according to the Keyboard API:
keyboard.press(hotkey) emulates pressing a hotkey on keyboard.
keyboard.release(hotkey) emulates releasing a hotkey on keyboard.
A hotkey is an key number, key name, or combination of two or more keys.

keyboard.press_and_release(hotkey) or keyboard.send(hotkey) emulates pressing and releasing a key or hotkey.
Pressing and releasing behaviour depends on values of do_press and do_release when using keyboard.send().

For example:

keyboard.send('space', do_press=True, do_release=True)

will emulate pressing and releasing space key, but:

keyboard.send('space', do_press=False, do_release=True)

will emulate only releasing space key.

keyboard.is_pressed(key) returns True if a specified key has been pressed, and False otherwise


Hope I've helped!

2 of 2
0

keyboard.is_pressed() is basically checking if a certain key code is pressed. If you put keyboard.is_pressed('x'), it will basically check if the letter x is being pressed, using its keycode, 88.

On the other hand, I can see that the majority of the script works, checking if 'u' is pressed, and then 'elseif's appear fine, but I don't know fully why this part, keyboard.release('w'), is at the very bottom. I suggest either removing this line lines:

    else: # (this line is fine)
        print(4) # (this line is fine)
        keyboard.release('w')

and adjusting the lines a wee bit for this completed code!

while True:
    if keyboard.is_pressed('u'):
        keyboard.press('w')
        keyboard.release('w')
        print(0)
    elif keyboard.is_pressed('j'):
        #keyboard.press_and_release('s')
        print(1)
    elif keyboard.is_pressed('k'):
         #keyboard.press_and_release('d')
         print(2)
    elif keyboard.is_pressed('h'):
        #keyboard.press_and_release('a')
        print(3)
    else:
        print("No Key pressed.") #alternatively, you can keep it as print(4).

Hope this helped, despite being over 4 years late.

๐ŸŒ
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. To be notified about callback errors, call Thread.join on the listener instance: from pynput import keyboard class MyException(Exception): pass def on_press(key): if key == keyboard.Key.esc: raise MyException(key) # Collect events until released with keyboard.Listener( on_press=on_press) as listener: try: listener.join() except MyException as e: print('{0} was pressed'.format(e.args[0]))
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-9019.html
keyboard.is_pressed attribute error
March 17, 2018 - Hello all I'm totally new to python and try to walk before I can crawl. The intention of the below code is to save serial input (received from an Arduino) to a file for as long as the application runs. The application can be interrupted by a keypre...
๐ŸŒ
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 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!

๐ŸŒ
Raspberry Pi Forums
forums.raspberrypi.com โ€บ board index โ€บ programming โ€บ python
Reading key presses in Python (without pausing execution) - Raspberry Pi Forums
Use The Keyboard Library For Python Terminal Replace "X.XX" with your python version or remove it if installed only one version ... import keyboard while True: if keyboard.is_pressed('a'): print('a key has ben pressed') print(1) print(1+2)
๐ŸŒ
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 - In this script, we first import the keyboard library. We then define a function on_key_event, which will be called every time a key event occurs. Inside this function, we check if the event type is 'down', meaning a key press.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ need help stopping an infinite loop with a key press
r/learnpython on Reddit: Need help stopping an infinite loop with a key press
December 28, 2022 -

Hi guys, so my goal for this program is to have the program continuously print "test". I want the program to stop printing "test" immediately once the user types in a specific key (ex. Enter, Down Arrow, a) and store a string in the variable "key_pressed". The way this program currently works, it will only stop the loop if the user is pressing the key right when the "if keyboard.is_pressed("a")" line is active. I don't know how to make this work, do you guys have any ideas?

import time
import keyboard

while True:
    time.sleep(0.5)  # pause for half a second
    print("test")

    if keyboard.is_pressed("a"):  # check if the A key is pressed (I want to be able to detect other keys such as the Down arrow key)
        key_pressed = str("A was pressed")
        break # exit the loop

print(key_pressed)

๐ŸŒ
Nitratine
nitratine.net โ€บ blog โ€บ post โ€บ simulate-keypresses-in-python
Simulate Keypresses In Python - Nitratine
December 16, 2017 - Using keyboard.press we can press keys and with keyboard.release we can release a key. This allows us to type a key by pressing and releasing. You can only supply this method with one key at a time. Here is an example of how to type the letter 'a'.
๐ŸŒ
pytz
pythonhosted.org โ€บ pynput โ€บ keyboard.html
Handling the keyboard โ€” pynput 1.1.2 documentation
Executes a block with some keys pressed. ... Releases a key. A key may be either a string of length 1, one of the Key members or a KeyCode. Strings will be transformed to KeyCode using KeyCode.char(). Members of Key will be translated to their value(). ... Whether any shift key is pressed, ...
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Using keyboard in my program - Python Help - Discussions on Python.org
June 2, 2023 - Hi guys, Iโ€™m new to python and today I want to add keyboard support to my program, namely the ability to exit the program by pressing โ€˜escโ€™, but itโ€™s isnโ€™t work, a screenshot will tell you more about it.