Open In App

Keyboard module in Python

Last Updated : 12 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

  • It helps to enter keys, record the keyboard activities and block the keys until a specified key is entered and simulate the keys.
  • It captures all keys, even onscreen keyboard events are also captured.
  • Keyboard module supports complex hotkeys.
  • Using this module we can listen and send keyboard events.
  • It works on both windows and linux operating system.

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:

  • keyboard.write() writes the text “GEEKS FOR GEEKS” to the output.
  • keyboard.press_and_release() simulates pressing and releasing the ‘Shift + R’, ‘Shift + K’, and ‘Enter’ keys.
  • keyboard.wait() pauses the program execution and waits until the ‘Ctrl’ key is pressed to proceed.

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:

  • keyboard.add_hotkey() assigns the action of writing “Geek” when the ‘a’ key is pressed.
  • A second hotkey (ctrl + shift + a) prints a message when pressed.
  • keyboard.wait(‘esc’) pauses the program until the ‘Esc’ key is pressed, terminating the program.

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:

  • keyboard.record() records all key presses until the ‘Esc’ key is pressed.
  • keyboard.play() replays the recorded key events at normal speed (speed_factor = 1).


Next Article

Similar Reads