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
๐ŸŒ
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.
๐ŸŒ
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)
๐ŸŒ
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
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()
๐ŸŒ
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.
๐ŸŒ
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")
๐ŸŒ
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.
Find elsewhere
๐ŸŒ
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 - This module provides a simple and efficient way to listen for keyboard events in your Python programs. To wait for a keypress, you simply need to create an instance of the `keyboard.Listener` class and define a callback function that will be called every time a key is pressed or released.
๐ŸŒ
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.
๐ŸŒ
GitHub
github.com โ€บ gauthsvenkat โ€บ pyKey
GitHub - gauthsvenkat/pyKey: A python library to simulate keyboard presses ยท GitHub
A python library to simulate keyboard presses. Contribute to gauthsvenkat/pyKey development by creating an account on GitHub.
Starred by 56 users
Forked by 6 users
Languages ย  Python
๐ŸŒ
Read the Docs
pynput.readthedocs.io โ€บ en โ€บ latest โ€บ keyboard.html
Handling the keyboard โ€” pynput 1.7.6 documentation
This method will send all key presses and releases necessary to type all characters in the string. class pynput.keyboard.Listener(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.
๐ŸŒ
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.

๐ŸŒ
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.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ 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.
๐ŸŒ
pytz
pythonhosted.org โ€บ pynput โ€บ keyboard.html
Handling the keyboard โ€” pynput 1.1.2 documentation
Starting a keyboard listener may be subject to some restrictions on your platform. ... The process must run as root. Your application must be white listed under Enable access for assistive devices. Note that this might require that you package your application, since otherwise the entire Python installation must be white listed.
๐ŸŒ
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 ...
๐ŸŒ
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)
๐ŸŒ
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.