Keyboard module in Python (original) (raw)

Last Updated : 12 Apr, 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.

Installation:

To install the keyboard module, run the following command:

pip install keyboard

Examples of Keyboard Module

Example 1: Simulating Key Presses and Blocking Keys

This code demonstrates how to simulate key presses and block the execution until a specific key is pressed using the **keyboard module.

Python `

import keyboard

keyboard.write("GEEKS FOR GEEKS\n")

keyboard.press_and_release('shift + r, shift + k, \n') keyboard.press_and_release('R, K')

keyboard.wait('Ctrl')

`

**Output:

GEEKS FOR GEEKS
RK
rk

**Explanation:

Example 2: Using Hotkeys with Keyboard Module

This code shows how to use hotkeys with the **keyboard module to trigger actions when specific keys or key combinations are pressed.

Python `

import keyboard

keyboard.add_hotkey('a', lambda: keyboard.write('Geek')) keyboard.add_hotkey('ctrl + shift + a', print, args =('you entered', 'hotkey'))

keyboard.wait('esc')

`

**Output

aGeek
you entered hotkey

**Explanation:

Example 3: Recording and Playing Key Events

This code demonstrates how to record and replay key presses using the **keyboard module.

Python `

import keyboard

rk = keyboard.record(until ='Esc')

keyboard.play(rk, speed_factor = 1)

`

**Output

www.geeksforgeeks.org

**Explanation: