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
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
🌐
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.
Discussions

keylistener - Key Listeners in python? - Stack Overflow
Global event hook on all keyboards (captures keys regardless of focus). Listen and sends keyboard events. Works with Windows and Linux (requires sudo), with experimental OS X support (thanks @glitchassassin!). Pure Python, no C modules to be compiled. Zero dependencies. More on stackoverflow.com
🌐 stackoverflow.com
python - How to generate keyboard events? - Stack Overflow
short summary: I am trying to create a program that will send keyboard events to the computer that for all purposes the simulated events should be treated as actual keystrokes on the keyboard. or... More on stackoverflow.com
🌐 stackoverflow.com
Detect key input in Python - Stack Overflow
try: # In order to be able to import ... event_handle) root.mainloop() ... Its very difficult to do without a module. But pynput is a core package. ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... 2 Python: How can I detect keyboard input in a ... 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
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()
🌐
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 454 users
Languages   Python 99.7% | Makefile 0.3%
Top answer
1 of 7
61

I was searching for a simple solution without window focus. Jayk's answer, pynput, works perfect for me. Here is the example how I use it.

from pynput import keyboard

def on_press(key):
    if key == keyboard.Key.esc:
        return False  # stop listener
    try:
        k = key.char  # single-char keys
    except:
        k = key.name  # other keys
    if k in ['1', '2', 'left', 'right']:  # keys of interest
        # self.keys.append(k)  # store it in global-like variable
        print('Key pressed: ' + k)
        return False  # stop listener; remove this if want more keys

listener = keyboard.Listener(on_press=on_press)
listener.start()  # start to listen on a separate thread
listener.join()  # remove if main thread is polling self.keys
2 of 7
33

It's unfortunately not so easy to do that. If you're trying to make some sort of text user interface, you may want to look into curses. If you want to display things like you normally would in a terminal, but want input like that, then you'll have to work with termios, which unfortunately appears to be poorly documented in Python. Neither of these options are that simple, though, unfortunately. Additionally, they do not work under Windows; if you need them to work under Windows, you'll have to use PDCurses as a replacement for curses or pywin32 rather than termios.


I was able to get this working decently. It prints out the hexadecimal representation of keys you type. As I said in the comments of your question, arrows are tricky; I think you'll agree.

#!/usr/bin/env python
import sys
import termios
import contextlib


@contextlib.contextmanager
def raw_mode(file):
    old_attrs = termios.tcgetattr(file.fileno())
    new_attrs = old_attrs[:]
    new_attrs[3] = new_attrs[3] & ~(termios.ECHO | termios.ICANON)
    try:
        termios.tcsetattr(file.fileno(), termios.TCSADRAIN, new_attrs)
        yield
    finally:
        termios.tcsetattr(file.fileno(), termios.TCSADRAIN, old_attrs)


def main():
    print 'exit with ^C or ^D'
    with raw_mode(sys.stdin):
        try:
            while True:
                ch = sys.stdin.read(1)
                if not ch or ch == chr(4):
                    break
                print '%02x' % ord(ch),
        except (KeyboardInterrupt, EOFError):
            pass


if __name__ == '__main__':
    main()
Top answer
1 of 12
150

It can be done using ctypes:

import ctypes
from ctypes import wintypes
import time

user32 = ctypes.WinDLL('user32', use_last_error=True)

INPUT_MOUSE    = 0
INPUT_KEYBOARD = 1
INPUT_HARDWARE = 2

KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP       = 0x0002
KEYEVENTF_UNICODE     = 0x0004
KEYEVENTF_SCANCODE    = 0x0008

MAPVK_VK_TO_VSC = 0

# msdn.microsoft.com/en-us/library/dd375731
VK_TAB  = 0x09
VK_MENU = 0x12

# C struct definitions

wintypes.ULONG_PTR = wintypes.WPARAM

class MOUSEINPUT(ctypes.Structure):
    _fields_ = (("dx",          wintypes.LONG),
                ("dy",          wintypes.LONG),
                ("mouseData",   wintypes.DWORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

class KEYBDINPUT(ctypes.Structure):
    _fields_ = (("wVk",         wintypes.WORD),
                ("wScan",       wintypes.WORD),
                ("dwFlags",     wintypes.DWORD),
                ("time",        wintypes.DWORD),
                ("dwExtraInfo", wintypes.ULONG_PTR))

    def __init__(self, *args, **kwds):
        super(KEYBDINPUT, self).__init__(*args, **kwds)
        # some programs use the scan code even if KEYEVENTF_SCANCODE
        # isn't set in dwFflags, so attempt to map the correct code.
        if not self.dwFlags & KEYEVENTF_UNICODE:
            self.wScan = user32.MapVirtualKeyExW(self.wVk,
                                                 MAPVK_VK_TO_VSC, 0)

class HARDWAREINPUT(ctypes.Structure):
    _fields_ = (("uMsg",    wintypes.DWORD),
                ("wParamL", wintypes.WORD),
                ("wParamH", wintypes.WORD))

class INPUT(ctypes.Structure):
    class _INPUT(ctypes.Union):
        _fields_ = (("ki", KEYBDINPUT),
                    ("mi", MOUSEINPUT),
                    ("hi", HARDWAREINPUT))
    _anonymous_ = ("_input",)
    _fields_ = (("type",   wintypes.DWORD),
                ("_input", _INPUT))

LPINPUT = ctypes.POINTER(INPUT)

def _check_count(result, func, args):
    if result == 0:
        raise ctypes.WinError(ctypes.get_last_error())
    return args

user32.SendInput.errcheck = _check_count
user32.SendInput.argtypes = (wintypes.UINT, # nInputs
                             LPINPUT,       # pInputs
                             ctypes.c_int)  # cbSize

# Functions

def PressKey(hexKeyCode):
    x = INPUT(type=INPUT_KEYBOARD,
              ki=KEYBDINPUT(wVk=hexKeyCode))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

def ReleaseKey(hexKeyCode):
    x = INPUT(type=INPUT_KEYBOARD,
              ki=KEYBDINPUT(wVk=hexKeyCode,
                            dwFlags=KEYEVENTF_KEYUP))
    user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))

def AltTab():
    """Press Alt+Tab and hold Alt key for 2 seconds
    in order to see the overlay.
    """
    PressKey(VK_MENU)   # Alt
    PressKey(VK_TAB)    # Tab
    ReleaseKey(VK_TAB)  # Tab~
    time.sleep(2)
    ReleaseKey(VK_MENU) # Alt~

if __name__ == "__main__":
    AltTab()

hexKeyCode is the virtual keyboard mapping as defined by the Windows API. The list of codes is available on MSDN: Virtual-Key Codes (Windows)

2 of 12
111

For both python3 and python2 you can use pyautogui (pip install pyautogui)

from pyautogui import press, typewrite, hotkey

press('a')
typewrite('quick brown fox')
hotkey('ctrl', 'w')

It's also crossplatform with Windows, OSX, and Ubuntu LTS.

Find elsewhere
🌐
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.
🌐
Medium
medium.com › @coldstart_coder › python-reading-mouse-and-keyboard-events-with-pynput-2c57b51ce65a
Python: Reading Mouse and Keyboard Events with Pynput | by Coldstart Coder | Medium
November 8, 2023 - This is going to be a similar setup to the mouse, pynput has a threaded keyboard listener that you will setup with callbacks. In the keyboard listener there are only 2 events we need, and that is on key press and on key release.
🌐
Nitratine
nitratine.net › blog › post › simulate-keypresses-in-python
Simulate Keypresses In Python - Nitratine
December 16, 2017 - 16 Dec 2017 YouTube python keyboard pynput 6 min read · 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. ... If you haven't used or setup pip before, go to my tutorial at how-to-setup-pythons-pip to setup pip. We will be using the pynput module to listen to mouse events...
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-detect-if-a-specific-key-pressed-using-python
How to detect if a specific key pressed using Python? - GeeksforGeeks
October 13, 2022 - Python3 · from pynput.keyboard import Key, Listener def show(key): print('\nYou Entered {0}'.format( key)) if key == Key.delete: # Stop listener return False # Collect all event until released with Listener(on_press = show) as listener: listener.join() Output: Example 2: Here you can detect a specific key is being been pressed or not.
🌐
Roadsi
roadsi.de › blog › python-and-keyboard-events
Python And Keyboard Events — Roadside
August 24, 2016 - And for me, Python is a great language to do that. It's batteries included approach to many problems makes it super easy to hack together a script for almost any job, and if you look at a library like Click make building command-line clients a piece of cake. If you haven't heard of it, check out my talk at PyCon US 2016. Why am I rambling on about this? Well, with all of these libraries and included batteries, you'd expect getting key press events from the commandline would also be a 🍰. But far from it!
🌐
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.
🌐
PyPI
pypi.org › project › pynput
pynput · PyPI
Corrected name of mouse input field when sending click and scroll events. Corrected use of ctypes on Windows. Use thread identifiers to identify threads, not Thread instances. Corrected bugs which prevented the library from being used on Python 3. Changed license to LGPL. Corrected minor bugs and inconsistencies. Corrected and extended documentation. Added support for monitoring the keyboard.
      » pip install pynput
    
Published   Mar 17, 2025
Version   1.8.1
🌐
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.