Keyboard module in Python

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.

Install using this command:

pip install keyboard

Example #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Using Keyboard module in Python
import keyboard
  
# It writes the content to output
keyboard.write("GEEKS FOR GEEKS\n")
  
# It writes the keys r, k and endofline 
keyboard.press_and_release('shift + r, shift + k, \n')
keyboard.press_and_release('R, K')
  
# it blocks until ctrl is pressed
keyboard.wait('Ctrl')

chevron_right


Output:

GEEKS FOR GEEKS 
RK
rk

 
Example #2: Keyboard module to enter hotkeys.



filter_none

edit
close

play_arrow

link
brightness_4
code

# Keyboard module in Python
import keyboard
  
# press a to print rk
keyboard.add_hotkey('a', lambda: keyboard.write('Geek'))
keyboard.add_hotkey('ctrl + shift + a', print, args =('you entered', 'hotkey'))
  
keyboard.wait('esc')

chevron_right


Output:

ark
you entered hotkey

 
Example #3: Keyboard module also used to record all the keyboard activities and replay them using play method.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Keyboard module in Python
import keyboard
  
# It records all the keys until escape is pressed
rk = keyboard.record(until ='Esc')
  
# It replay back the all keys
keyboard.play(rk, speed_factor = 1)

chevron_right


Output:

www.geeksforgeeks.org 

 
Reference : https://pypi.org/project/keyboard/

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.