🌐
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
🌐
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]¶
Discussions

How Can i Simulate Key Presses In Python ?
🌐 r/learnpython
6
2
September 21, 2021
python - How to detect key presses? - Stack Overflow
I am making a stopwatch type program ... a key is pressed (such as p for pause and s for stop), and I would not like it to be something like raw_input, which waits for the user's input before continuing execution. ... I would like to make this cross-platform but, if that is not possible, then my main development target is Linux. ... Python has a keyboard module with ... More on stackoverflow.com
🌐 stackoverflow.com
How to detect keypress in python using keyboard module? - Stack Overflow
Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal. ... Find centralized, trusted content and collaborate around the technologies you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I am making a program in python to detect what key is pressed and based on my keyboard ... More on stackoverflow.com
🌐 stackoverflow.com
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
12
0
June 2, 2023
🌐
Stack Abuse
stackabuse.com › guide-to-pythons-keyboard-module
Guide to Python's keyboard Module
October 24, 2023 - keyboard.press(key) - presses a key and holds until the release(key) function is called.
🌐
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.
🌐
pytz
pythonhosted.org › pynput › keyboard.html
Handling the keyboard — pynput 1.1.2 documentation
from pynput.keyboard import Key, Controller keyboard = Controller() # Press and release space keyboard.press(Key.space) keyboard.release(Key.space) # Type a lower case A; this will work even if no key on the # physical keyboard is labelled 'A' keyboard.press('a') keyboard.release('a') # Type two upper case As keyboard.press('A') keyboard.release('A') with keyboard.pressed(Key.shift): keyboard.press('a') keyboard.release('a') # Type 'Hello World' using the shortcut type method keyboard.type('Hello World')
🌐
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.

Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › keyboard-module-in-python
Keyboard module in Python - GeeksforGeeks
April 12, 2025 - keyboard.press_and_release() simulates pressing and releasing the 'Shift + R', 'Shift + K', and 'Enter' keys.
🌐
GitHub
github.com › boppreh › keyboard
GitHub - boppreh/keyboard: Hook and simulate global keyboard events on Windows and Linux. · GitHub
February 13, 2026 - Take full control of your keyboard with this small Python library. Hook global events, register hotkeys, simulate key presses and much more.
Starred by 4K users
Forked by 455 users
Languages   Python 99.7% | Makefile 0.3%
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.
🌐
Playwright
playwright.dev › keyboard
Keyboard | Playwright Python
After the key is pressed once, subsequent calls to keyboard.down() will have repeat set to true. To release the key, use keyboard.up(). ... Modifier keys DO influence keyboard.down. Holding down Shift will type the text in upper case.
🌐
PyTutorial
pytutorial.com › master-python-keyboard-automation-with-press_and_release
PyTutorial | Master Python Keyboard Automation with press_and_release()
November 23, 2024 - Keyboard automation in Python becomes seamless with pynput.keyboard.press_and_release(), a powerful function that simulates keyboard key presses and releases in a single operation.
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
Reading key presses in Python (without pausing execution) - Raspberry Pi Forums
November 17, 2021 - Have a search for those words and see what comes up. Sorry, on my phone so can't quickly find some links for you. RPi Information Screen: plugin based system for displaying weather, travel information, football scores etc. ... 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 - ... There are a lot of things happening in the above example. The press() function will be executed when we press the key and print the key. Similarly, the on_release() function will be executed when the key is released.
🌐
Nitratine
nitratine.net › blog › post › how-to-detect-key-presses-in-python
How to Detect Key Presses In Python - Nitratine
April 7, 2020 - Everything being on a new line with both key presses and releases can be very helpful for identifying sequences but can be a bit hard to read. Here is a modified script that can put everything on one line and enters when enter is pressed. from pynput.keyboard import Listener, Key filename = "key_log.txt" # The file to write characters to def on_press(key): f = open(filename, 'a') # Open the file if hasattr(key, 'char'): # Write the character pressed if available f.write(key.char) elif key == Key.space: # If space was pressed, write a space f.write(' ') elif key == Key.enter: # If enter was pre
🌐
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 - 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'. Thanks in advanced if you can share some experience with me · Solved! Go to Solution. ... The pynput package can be used to simulate keystrokes. ... from pynput.keyboard import Key, Controller keyboard = Controller() keyboard.press(Key.enter) keyboard.release(Key.enter)
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.