First of all, you forgot to close the strings on lines 4 and 6.

But your main issue is that you call keyboard.read_key() once for each arm of your if statement. This makes your code wait for a keypress, check if it's 'enter', then wait for another keypress, check if it's 'q', and so on.

What you should do is save the key to a variable, then check the variable. It should look something like this:

import keyboard
while True:
    key = keyboard.read_key()
    if key == 'enter':
        print('Enter is pressed')
    if key == 'q':
        print('Quitting the program')
        break
    if key == 's':
        print('Skiping the things')
Answer from Jason on Stack Overflow
🌐
PyPI
pypi.org › project › keyboard
keyboard · PyPI
Listen and send keyboard events. Works with Windows and Linux (requires sudo), with experimental OS X support (thanks @glitchassassin!). Pure Python, no C modules to be compiled.
      » pip install keyboard
    
Published   Mar 23, 2020
Version   0.13.5
🌐
GitHub
github.com › boppreh › keyboard
GitHub - boppreh/keyboard: Hook and simulate global keyboard events on Windows and Linux. · GitHub
February 13, 2026 - Listen and send keyboard events. Works with Windows and Linux (requires sudo), with experimental OS X support (thanks @glitchassassin!). Pure Python, no C modules to be compiled.
Starred by 4K users
Forked by 454 users
Languages   Python 99.7% | Makefile 0.3%
Discussions

How to detect keypress in python using keyboard module? - Stack Overflow
I am making a program in python to detect what key is pressed and based on my keyboard it will make a decision. I want to implement it using keyboard module in python. I would do something like th... More on stackoverflow.com
🌐 stackoverflow.com
Is there a doc for the keyboard library?
It's not part of the standard library so it's not going to be on the official Python docs. It looks like it hasn't been updated in years. https://github.com/boppreh/keyboard More on reddit.com
🌐 r/learnpython
2
4
October 10, 2024
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
Cross platform keyboard input
I couldn’t find a cross platform library for keyboard input that doesn’t also need special priviliges: curses: doesn’t work on Windows and emposes arbitrary restrictions on output pip install keyboard: requires root on macOS, can’t be included with your code and acts like a keylogger ... More on discuss.python.org
🌐 discuss.python.org
0
2
April 26, 2024
🌐
GeeksforGeeks
geeksforgeeks.org › python › keyboard-module-in-python
Keyboard module in Python - GeeksforGeeks
April 12, 2025 - It's a small Python library which can hook global events, register hotkeys, simulate key presses and much more. It helps to enter keys, record the keyboard activities and block the keys until a specified key is entered and simulate the keys.
🌐
Read the Docs
pynput.readthedocs.io › en › latest › keyboard.html
Handling the keyboard — pynput 1.7.6 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')
🌐
The Python Code
thepythoncode.com › article › control-keyboard-python
Keyboard module: Controlling your Keyboard in Python - The Python Code
Learn how to use keyboard module in Python to take full control of your keyboard such as hooking global events, registering hotkeys, simulating key presses and releases and much more.
🌐
Reddit
reddit.com › r/learnpython › is there a doc for the keyboard library?
r/learnpython on Reddit: Is there a doc for the keyboard library?
October 10, 2024 -

I want to make a keylogger and learn more about the keyboard module. PyPI has a doc for it but I doesn't go in depth on what methods to input and what they mean.

I found the python standard library but the doc is not there
https://docs.python.org/3/library/index.html

I wanted to know where can I find the doc for it or where can I learn about the keyboard library?

It looks like the module takes Windows keys, will the keyboard library work with Mac as well and can I use the same key inputs when coding?

Also, I am beginner in python will a Keylogger be a good beginner project?

Find elsewhere
🌐
Stack Abuse
stackabuse.com › guide-to-pythons-keyboard-module
Guide to Python's keyboard Module
October 24, 2023 - Whether it's repeatable (ethical) web scraping after some time period, starting some programs on a computer start up, or automating sending mundane e-mails, Python has a lot of modules that make your life easier. One of these is a module called keyboard, and it takes full control of your keyboard.
🌐
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.
🌐
GitHub
github.com › makerdiary › python-keyboard
GitHub - makerdiary/python-keyboard: A hand-wired USB & Bluetooth keyboard powered by Python and more · GitHub
A hand-wired USB & Bluetooth keyboard powered by Python and more - makerdiary/python-keyboard
Starred by 500 users
Forked by 59 users
Languages   Python
🌐
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.
🌐
YouTube
youtube.com › watch
How to control the keyboard with Python in 2020! EASY & FAST(Pynput) - YouTube
Learn how to control the keyboard with Python Easy & Fast! You could use this information to make an autotyper of your own with Python and Pynput. Pynput is ...
Published   June 23, 2020
🌐
Real Python
realpython.com › python-keyboard-input
How to Read User Input From the Keyboard in Python – Real Python
February 20, 2024 - The input() function is the simplest way to get keyboard data from the user in Python. When called, it asks the user for input with a prompt that you specify, and it waits for the user to type a response and press the Enter key before continuing.
🌐
Python.org
discuss.python.org › python help
Cross platform keyboard input - Python Help - Discussions on Python.org
April 26, 2024 - I couldn’t find a cross platform library for keyboard input that doesn’t also need special priviliges: curses: doesn’t work on Windows and emposes arbitrary restrictions on output pip install keyboard: requires root on macOS, can’t be included with your code and acts like a keylogger on Windows pip install pynput: not trusted on macOS and can’t be included with your code So, I wrote my own, AnsI/O, providing a low-level interface for input & output.
🌐
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.
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.

🌐
Reddit
reddit.com › r/learnpython › keyboard module
r/learnpython on Reddit: Keyboard module
March 16, 2023 -

So recently i decided to learn how to code on python, and i tried downloading the keyboard module.

I went down to my cmd, typed "pip install keyboard", succesfull.
Tried to use it in python using "import keyboard", not so successfull.
Got this error messsage:

" import keyboard
ModuleNotFoundError: No module named 'keyboard'"

I tried uninstalling keyboard from my cmd, rebooting my pc, using the "pip3 install keyboard", nothing worked. I read somewhere that it might be due to an interpreter problem, but i don't knoow how to fix it.

Hope some of y'all could help me :)

🌐
Javatpoint
javatpoint.com › keyboard-module-in-python
Keyboard Module in Python - Javatpoint
Keyboard Module in Python with python, tutorial, tkinter, button, overview, entry, checkbutton, canvas, frame, environment set-up, first python program, operators, etc.
🌐
pytz
pythonhosted.org › pynput › keyboard.html
Handling the keyboard — pynput 1.1.2 documentation
The package pynput.keyboard contains classes for controlling and monitoring the keyboard.
🌐
Python.org
discuss.python.org › python help
Installing keyboard module blues - Python Help - Discussions on Python.org
October 22, 2024 - SO if this button on the remote controle is pressed python has to give a arrow up. I wanted to use the python-keyboard module for that. Now, installing it is a bit problematic. I have tried to use pip install keyboard. But then i get the “This environment is externally managed” message.