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
🌐
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.
      » pip install keyboard
    
Published   Mar 23, 2020
Version   0.13.5
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()
Discussions

How do you hold down keys using the "Keyboard" module in python? - Stack Overflow
I am creating a racing game AI, and am trying to get it to hold down keys rather than it just tapping the keys on the keyboard really fast, such as holding down "w" to accelerate rather than just feather tapping it. Is there any way to make the keyboard module in python press and hold down ... More on stackoverflow.com
🌐 stackoverflow.com
keypress - Key Presses in Python - Stack Overflow
It "presses and holds down a hotkey", see: github.com/boppreh/keyboard#keyboardpresshotkey 2021-11-27T16:13:32.383Z+00:00 ... This works, but does not answer the question, so I will vote it up but I can't accept it as the answer. 2008-09-25T23:37:49.263Z+00:00 ... If you're platform is Windows, I wouldn't actually recommend Python... More on stackoverflow.com
🌐 stackoverflow.com
How to make a script that will hold down a key for x seconds
I am very new to python, I have been coding in Lua for about 3 years but just the past couple of days I have been learning python, anyways I am trying to make a script that will hold down the “e” key on my keyboard for x… More on discuss.python.org
🌐 discuss.python.org
0
0
December 12, 2022
Using keyboard in my program
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. More on discuss.python.org
🌐 discuss.python.org
0
0
June 2, 2023
🌐
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.
🌐
PyAutoGUI
pyautogui.readthedocs.io › en › latest › keyboard.html
Keyboard Control Functions — PyAutoGUI documentation
See KEYBOARD_KEYS. >>> with pyautogui.hold('shift'): pyautogui.press(['left', 'left', 'left']) ... >>> pyautogui.keyDown('shift') # hold down the shift key >>> pyautogui.press('left') # press the left arrow key >>> pyautogui.press('left') # press the left arrow key >>> pyautogui.press('left') # press the left arrow key >>> pyautogui.keyUp('shift') # release the shift key
Top answer
1 of 2
1

Your thing of using keyboard.press('w') works, but it just doesn't show as it would when you hold a key. You can test this with some kind of game that uses "w" as a movement key, then running your script and you should move forwards for the said amount of time.

2 of 2
1

I think that the keyboard module is not as good of a choice to hold the key down as @Alderven mentioned, but it is great for detecting key presses instead if that helps your code. I would recommend using pyautogui. For example:

import pyautogui
import time

def accelerate():
    pyautogui.keyDown('w') #holds the key down
    time.sleep(5) #could be replaced with detecting an input
    pyautogui.keyUp('w') #releases the key
    return 0

Note: When you run the program, in the shell, there will not be a bunch of w's being typed as you'd expect, like this: wwwwwwwwwwwwwwwwwww. Instead, at least for me, only one w was pressed. I don't know why this occurs, although I can tell you that the key w is being pressed and this is NOT an error. I know this because I tried playing a game that involved pressing the key w (just an online web browser racing game), and the code worked. If you truly wanted the output "wwwwwwwwwwwwwwwwwwwwwwwwwww", then you can just use pyautogui's write() function:

pyautogui.write("wwwwwwwwwwwwwwwwwwwwwwwwwwwwww")

and there you go. Since you were referring to a racing game that doesn't involve getting a string of w's, this probably doesn't apply to your code.

If you want to wait for a certain input instead of holding down the key for a certain amount of time like I did, you could instead replace this:

time.sleep(5)

with this:

while True:
    if keyboard.is_pressed('del')
    break 

You would have to import the keyboard module for that to work, since pyautogui cannot detect key presses.

Pynput is another great choice of module besides pyautogui, and there are a lot of other great Stack Overflow posts about pyautogui and pynput, so if this solution doesn't work, you should check those out if you haven't already. It would also help if you clarified about the context of the code, as mentioned by @OysterShucker. If it is a racing game AI, why does it need the user to input the del key so the AI knows when to release the w key, and why not automate it? Those are questions that I would recommend answering.

🌐
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.
Find elsewhere
🌐
Python.org
discuss.python.org › python help
How to make a script that will hold down a key for x seconds - Python Help - Discussions on Python.org
December 12, 2022 - I am very new to python, I have been coding in Lua for about 3 years but just the past couple of days I have been learning python, anyways I am trying to make a script that will hold down the “e” key on my keyboard for x…
🌐
GitHub
github.com › boppreh › keyboard
GitHub - boppreh/keyboard: Hook and simulate global keyboard events on Windows and Linux. · GitHub
February 13, 2026 - Presses and holds down a hotkey (see send). ... Releases a hotkey (see send). ... Returns True if the key is pressed. is_pressed(57) #-> True is_pressed('space') #-> True is_pressed('ctrl+space') #-> True ...
Starred by 4K users
Forked by 454 users
Languages   Python 99.7% | Makefile 0.3%
🌐
Stack Abuse
stackabuse.com › guide-to-pythons-keyboard-module
Guide to Python's keyboard Module
October 24, 2023 - The press() function presses a key and releases it when you call release() on the same key. Note that you can't sleep() for some time to simulate holding down a key: ... Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat ...
🌐
The Python Code
thepythoncode.com › article › control-keyboard-python
Keyboard module: Controlling your Keyboard in Python - The Python Code
The + operator means we press both buttons at the same time. You can also use multi-step hotkeys: # send ALT+F4 in the same time, and then send space, # (be carful, this will close any current open window) keyboard.send("alt+F4, space")
🌐
Read the Docs
pynput.readthedocs.io › en › latest › keyboard.html
Handling the keyboard — pynput 1.7.6 documentation
A listener for keyboard events. Instances of this class can be used as context managers. This is equivalent to the following code: listener.start() try: listener.wait() with_statements() finally: listener.stop() This class inherits from threading.Thread and supports all its methods. It will set daemon to True when created. __init__(on_press=None, on_release=None, suppress=False, **kwargs)[source]¶
🌐
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.
🌐
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.
🌐
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.
🌐
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.
🌐
pytz
pythonhosted.org › pyglet › programming_guide › keyboard_events.html
Keyboard events
Previous: Working with ...Next: Text and ...Programming Guide » Working with ... » 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.
🌐
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.

🌐
GeeksforGeeks
geeksforgeeks.org › python › keyboard-module-in-python
Keyboard module in Python - GeeksforGeeks
April 12, 2025 - Python provides a library named keyboard which is used to get full control of the keyboard. It's a small Python library which can hook global events, register hotkeys, simulate key presses and much more.