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 can i simulate key presses in python ?
r/learnpython on Reddit: How Can i Simulate Key Presses In Python ?
September 21, 2021 -

Hi, i want to simulate key presses (and shortcuts) in Python on Linux. I have already looked into pynput, and while it works, it is not global. what i am trying to do is as follows: i am using kde plasma as a desktop environment, and so in kde plasma settings, i made a shortcut (ctrl + a) that triggers the audio applet. so when i press that shortcut, the audio applet will open up. now what i want to achieve is that when a specific condition happens in my program, i open the applet.

from pynput.keyboard import Key, Controller

keyboard = Controller()

key = "a"

key2 = Key.ctrl

keyboard.press(key)

keyboard.press(key2)

keyboard.release(key)

keyboard.release(key2)

and while it works, but it is not global, and what i mean by this is that when i run this script i see "a" in the terminal as if i pressed it in the terminal, and the applet does not open up.

so any help on how can i achieve this ?

EDIT: i found a so much easier solution that works like a charm. There is a linux package called xdotool that stimulates mouse and keyboard stuff. So with this simple command xdotool key ctrl+a . It works perfectly. So i would just use an os.system and execute this.

Discussions

keypress - Key Presses in Python - Stack Overflow
Is it possible to make it appear to a system that a key was pressed, for example I need to make A key be pressed thousands of times, and it is much to time consuming to do it manually, I would lik... More on stackoverflow.com
๐ŸŒ stackoverflow.com
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 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
Solved: How to perform a key press 'Enter' in Python? - Autodesk Community
So how can I send a 'Enter' in python to Fusion interface? imitate a key press 'Enter' then send it to Fusion to finish an operation? The only information I got now is the keycode of 'Enter'. EnterKeyCode 16777221 Enter Thanks in advanced if you can share some experience with me More on forums.autodesk.com
๐ŸŒ forums.autodesk.com
June 13, 2025
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ keyboard
keyboard ยท PyPI
Take full control of your keyboard with this small Python library. Hook global events, register hotkeys, simulate key presses and much more.
      ยป pip install keyboard
    
Published ย  Mar 23, 2020
Version ย  0.13.5
๐ŸŒ
Nitratine
nitratine.net โ€บ blog โ€บ post โ€บ simulate-keypresses-in-python
Simulate Keypresses In Python - Nitratine
December 16, 2017 - This demonstrates how to press keys with Python. Using pynput we are able to simulate key presses into any window. This will show you how to press and release a key, type special keys and type a sentence.
๐ŸŒ
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 - Here we are importing the keyboard Module and with the help of read_key() method checking what key is pressed. ... In this method, we will use pynput Python module to detecting any key press. "pynput.keyboard" contains classes for controlling and monitoring 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.
Find elsewhere
๐ŸŒ
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!
๐ŸŒ
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 - 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.
๐ŸŒ
Raspberry Pi Forums
forums.raspberrypi.com โ€บ board index โ€บ programming โ€บ python
Reading key presses in Python (without pausing execution) - Raspberry Pi Forums
November 17, 2021 - 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)
๐ŸŒ
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.
๐ŸŒ
Autodesk Community
forums.autodesk.com โ€บ t5 โ€บ fusion-api-and-scripts-forum โ€บ how-to-perform-a-key-press-enter-in-python โ€บ td-p โ€บ 13194950
Solved: How to perform a key press 'Enter' in Python? - Autodesk Community
June 13, 2025 - After most of the operation, I have to press 'Enter' to finish, 'Enter' is not in a easy position to press. Is that a way I can write a python script to perform a 'Enter' press? then binding it to 'SPACE', much more easy to press. I have already write some shortcut in Python to make it easy to work.
๐ŸŒ
GitHub
github.com โ€บ gauthsvenkat โ€บ pyKey
GitHub - gauthsvenkat/pyKey: A python library to simulate keyboard presses ยท GitHub
if seq is a string, each character ... is to be pressed and the time to hold the key for (in seconds) respectively. Will display the available keys and their corresponding scan codes (on windows) or xdotool name (on linux). The motivation for this project comes from sentdex's python plays gta ...
Starred by 56 users
Forked by 6 users
Languages ย  Python
๐ŸŒ
Playwright
playwright.dev โ€บ keyboard
Keyboard | Playwright Python
Keyboard provides an api for managing a virtual keyboard. The high level api is keyboard.type(), which takes raw characters and generates proper keydown, keypress/input, and keyup events on your page.
๐ŸŒ
Java2Blog
java2blog.com โ€บ home โ€บ python โ€บ detect keypress in python
Detect keypress in Python - Java2Blog
June 12, 2021 - The getch() function returns the key pressed in a byte string. Notice the b in the output. 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.
๐ŸŒ
pytz
pythonhosted.org โ€บ pynput โ€บ keyboard.html
Handling the keyboard โ€” pynput 1.1.2 documentation
Calls either press() or release() depending on the value of is_press. ... Types a string. This method will send all key presses and releases necessary to type all characters in the string.
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
pytz
pythonhosted.org โ€บ pyglet โ€บ programming_guide โ€บ keyboard_events.html
Keyboard events
The Window.on_key_press and Window.on_key_release events are fired when any key on the keyboard is pressed or released, respectively.