Overview of Python Keyboard Module
In an age defined by rapid technological advancement and digital innovation, the ability to automate mundane tasks has become a cornerstone of efficiency and productivity. From simplifying repetitive processes to orchestrating complex workflows, automation empowers individuals and organizations to focus their time and energy on endeavors that genuinely matter. At the heart of this automation revolution lies Python, a versatile programming language renowned for its simplicity, readability, and extensive library support. Among the myriad libraries available in the Python ecosystem, the keyboard module stands out as a powerful tool for automating keyboard interactions easily and precisely.
Welcome to “Mastering Python Keyboard Module: A Comprehensive Guide to Automating Keyboard Interactions.” In this definitive guide, we embark on a journey to unravel the mysteries of the Python keyboard module, exploring its myriad functionalities, Installation and Setup applications, and potential to revolutionize how we interact with computers.
Key Features and Capabilities:
The keyboard module boasts a range of features designed to simplify keyboard manipulation and automation. Some key capabilities include:
- Entering keys: The module enables users to simulate key presses, allowing for automated input in scripts and applications.
- Recording keyboard activities: Developers can use the keyboard module to capture and record keyboard events, facilitating tasks such as logging user input or monitoring keyboard usage.
- Blocking keys: The module enables users to block specific keys until they enter a designated key, granting control over keyboard input in various scenarios.
- Complex hotkeys: With support for complex hotkeys, the keyboard module enables developers to define custom key combinations for executing specific actions or commands.
Cross-Platform Compatibility:
One of the keyboard module’s key advantages is its cross-platform compatibility. It works seamlessly on Windows and Linux operating systems, ensuring developers can leverage its capabilities across different environments without any compatibility issues.
Table of Contents
Key takeaways
- The keyboard module is small and easy to use.
- It can simulate key presses, register hotkeys, and hook global events.
- You can use it to enter keys and record keyboard activities.
- You can even block any key of the keyboard.
- It captures all keys, including onscreen keyboard events.
- Operating systems: Linux and Windows are supported.
Installation and Setup
You can install this module via pip like this:
pip install keyboard.
You can now import it and start using this keyboard module. The keyboard module supports both versions of Python 2.x and 3.x.
If you use Linux, you must install this library as the root user. Otherwise, you will get this error:
ImportError: You must be root to use this library on Linux.
Also, when running your script, you should ensure that you have installed this on root privileges. For example,
$ sudo pip3 install keyboard
$ sudo python3 my_script.py
On Windows and MacOS, the procedure is easy because privilege management functions differently. You can install the module using pip and run your scripts without any steps. For example,
$ pip install keyboard
$ python my_script.py
Functions of Python keyboard module.
The keyboard module has various functions in Python. We have discussed some of them as follows.
1. The write() and wait() functions
The write() function is used to write messages to the keyboard. The message can be a string, a list of strings, and a single character. There is an optional field to wait before writing the message in the write() function. The system will write the message immediately if you don’t provide a delay value. For example,
Import keyboard
keyboard.write("educba")
The output is
Similarly, you can use the following commands to write:
Import keyboard
keyboard.write(['h','e','l','l','o',' ','e','d','u','c','b','a'])
This writes the list of characters to the keyboard immediately. The output is
It writes the character ‘e’ on the keyboard after a delay of 0.1 seconds.
keyboard.write('e', delay=0.5)
The output is
The wait() function pauses the program’s execution until the user presses a key. It returns the key that the user pressed. If no key is pressed, it returns None.
For example, it can be used to wait for a specific key to be pressed:
import keyboard
# Wait for the 'space' key to be pressed
keyboard.wait('space')
# Print a message after the 'space' key is pressed
print('Space was pressed, continuing...')
The program will wait until you hit the space bar. It won’t respond if you press any other key. Once you press the space bar, the program will react.
You can put it in a loop like this:
import keyboard
# Loop indefinitely
while True:
# Wait for the 'space' key to be pressed
keyboard.wait('space')
# Once 'space' is pressed, print a message
print('Space was pressed! Waiting for it again...')
You can put it in a loop like this:
import keyboard
# Loop indefinitely
while True:
# Wait for the 'space' key to be pressed
keyboard.wait('space')
# Once 'space' is pressed, print a message
print('Space was pressed! Waiting for it again...')
Press the spacebar to get a response
2. The press() and release() functions
If you want to press and hold a key of the keyboard, then you need to use press() of the keyboard. Once you are done with that task and wish to release that key, you will need to use the release() function of the keyboard module. The syntax is as follows:
keyboard.press(key)
keyboard.release(key)
Where the key is the key you want to press and release, the key can be a string, like ‘a’, ‘Enter’, ‘Space’. It can also be a Key object, like Key.space or Key.ctrl.
For example, the following code will press the ‘space’ key and then release it:
import keyboard
keyboard.press('space')
keyboard.release('space')
You can also use the press() and release() functions to simulate key combinations. For example,
import keyboard
# Press the "shift" key
keyboard.press("shift")
# Write "lowercase"
keyboard.write("educba")
# Release the "shift" key
keyboard.release("shift")
The output is:
Explanation
- The user pressed and held the shift key.
- They attempted to type ‘educba’ in lowercase.
- Because the shift key was held, the output appeared as ‘EDUCBA’ (uppercase).
- The user then released the shift key.
Similarly, we can write in lowercase if we provide uppercase letters.
These can be used to type text, fill out forms, create games and other interactive programs, etc. For example, we have written the text “educba” using the keyboard module’s press() and release() functions.
import keyboard
keyboard.press('e')
keyboard.release('e')
keyboard.press('d')
keyboard.release('d')
keyboard.press('u')
keyboard.release('u')
keyboard.press('c')
keyboard.release('c')
keyboard.press('b')
keyboard.release('b')
keyboard.press('a')
keyboard.release('a')
The output is
You can also use these functions to fill out forms and create a game in which players must press specific keys while playing.
3. The record() and play() functions:
You can record all our keyboard activities on the output screen. You can also replay them on the output screen itself. Consider the following example: record () and play() functions.
import keyboard
# Record keystrokes until the 'esc' key is pressed
recorded_events = keyboard.record(until='esc')
This will record all the keyboard activity until you press the ‘ESC’ key. If you want to view this activity, use the following print command.
# Print the recorded events
print(recorded_events)
Now, if you want to play back these recorded events, you can use this command:
# Play back the recorded events
keyboard.play(recorded_events)
This means that ‘shs’ was pressed while the events were recorded.
4. The send() function</h3
The send() function replaces the press() and release() functions. It sends keystrokes to the active window and application. You can type text and press the keys programmatically.
For example, the following command will send key ‘a’:
# Send a single keystroke
keyboard.send('a')
The output:
# Send special keys using keyboard.send()
keyboard.send('ctrl+c') # Send Ctrl+C (copy)
keyboard.send('ctrl+v') # Send Ctrl+V (paste)
keyboard.send('shift+5') # Send Shift+5 (type the '%' symbol)
The output is
5. The add_hotkey() function
Though you use the press() function to define shortcut keys, that is not the correct way to do so, as we should release those keys after using them. We have a specific method for defining keys: the add_hotkey() function.
For example,
import keyboard
# Define a hotkey combination and its corresponding callback function
keyboard.add_hotkey('ctrl+shift+a', lambda: print('Hotkey triggered!'))
Output:
In this code, we pressed the Ctrl+Shift+A keys simultaneously, which triggered the assigned lambda function and printed ‘Hotkey pressed!’
You can also call a function by using a specific hotkey. For example,
import keyboard
# Define a callback function
def my_callback():
print('Custom callback function called!')
# Register a hotkey with the defined callback function
keyboard.add_hotkey('ctrl+shift+b', my_callback)
When you press ctrl+shift+b, the given function will be called.
Handling Modifier Keys
Keyboard modifiers are keys that, when pressed together, change how another key operates typically. For example, Shift, Ctrl, Alt, Windows key, etc are modifier keys. You can use these keys with other keys to perform various functions, like copying, pasting, and executing shortcuts.
You can view all the available modifiers using:
keyboard.all_modifiers
It will display all modifiers:
You can use any of these modifier keys and other keys to simulate.
Simulating Key Presses
You can simulate keys to press in your script and generate keyboard input. These are useful for various purposes, such as testing, controlling applications, automating repetitive tasks, etc.
- You can use a keyboard.press() and keyboard.release() functions for single keys.
- You can use the keyboard.send() function for more than one key to send.
- The keyboard is available for use. To write text on the screen, use the write() function.
Advanced Concepts
1. Event Hooks
It would help if you listened to keyboard events, like key presses and releases. It helps create hotkeys, logging keystrokes, and trigger actions based on specific key combinations. The keyboard module also provides a hook event for this purpose.
- hook(callback)
It installs global listeners on all available keyboards. It invokes the callback each time a key is pressed and released. - unhook(remove)
It removes previously added hooks.
For example,
import keyboard
def on_key_event(event):
print(f'Key {event.name} {"pressed" if event.event_type == "down" else "released"}')
# Install the event hook
keyboard.hook(on_key_event)
# Wait for keys to be pressed
keyboard.wait('esc')
# Remove the event hook
keyboard.unhook(on_key_event)
It is listening now. It will record your events. When you press a key, it presses and releases it.
When you terminate with Ctrl+C, the keyboard module will automatically call the keyboard. Unhook () on the key event you press. As a result, the output will be ‘educba’.
2. Blocking Keys
You can also block specific keys regardless of modifiers on the keyboard.block_key() command. It can be useful if you want to prevent certain keys from being pressed during the execution of your script.
For example,
import keyboard
# Block the 'a' key regardless of modifiers
keyboard.block_key('a')
It will block the key ‘a’ from triggering any events.
3. Text Expansion (Abbreviations)
Text expansion is also known as abbreviation expansion. You can use the add_abbreviation() function to define abbreviations for long text and inputs. You can save them and utilize them for convenience purposes. For example, if you want to abbreviate [email protected] as @, then you need this command:
# Define an abbreviation and its expansion
keyboard.add_abbreviation("@", "[email protected]")
It will be added above the abbreviation. You can get that by typing ‘@’ followed by SPACE. It will return the full text that you have defined.
Typing ‘@’ followed by a SPACE will return the full text you’ve defined, adding it above the abbreviation.
# Define an abbreviation and its expansion
keyboard.add_abbreviation("@", "7530000000").)
Therefore, you should not add the same abbreviation again.
Practical Examples
There are various uses of the keyboard module in real life. We have explained some of them here.
1. Simple Game Control:
You can use the keyboard module to create simple game controls. You can move characters and trigger actions within a game. For example, you build shortcut keys for jumping, shooting, and interacting with objects.
import keyboard
def jump():
print("Jumping...\n")
def shoot():
print("Shooting...\n")
# Define hotkeys for game controls
keyboard.add_hotkey('space+c', jump)
keyboard.add_hotkey('space+v', shoot)
When you press Space+C and Space+V, it will call the defined functions accordingly.
You can also remove these defined hotkeys by using them.
# Remove the hotkeys
keyboard.unhook_all_hotkeys()
2. Automation Task:
Using the keyboard module, you can automate repetitive computer tasks. For instance, you can copy text using the Ctrl + C shortcut.
import keyboard
# Simulate pressing Ctrl+C to copy text
keyboard.press("ctrl")
keyboard.press("c")
keyboard.release("c")
keyboard.release("ctrl")
To copy text, press Ctrl and then C. Once the text is copied, you need to release these keys.
3. Custom Hotkey Tool:
You can create custom Hotkeys. For example,
import keyboard
import webbrowser
def open_browser():
webbrowser.open('https://www.educba.com')
# Define custom hotkey
keyboard.add_hotkey('ctrl+b', open_browser)
Now, when you press Ctrl+B, it will open the default browser on your computer and navigate to the website educba.com.
You can remove hotkeys once done by using them.
# Remove the hotkeys
keyboard.unhook_all_hotkeys()
Compatibility and Limitations
One third-party module is the keyboard module. To install it, use the pip package manager. As was previously mentioned, it serves a variety of purposes. It works with Linux, macOS, and Windows. But, there are some limitations. For example, it cannot report the device ID of events on Windows. Media keys might not be accurately detected and reported on Linux systems. You can only use the block key function on Windows.
Alternatives to the Keyboard Module
There are various alternatives to keyboard modules in Python, such as pynput, autopy, and PyAutoGUI. However, the choice depends on your needs and requirements. The Keyboard module is easy to use. If you need more features and cross-platform compatibility, you can choose any other alternative keyboard module.
Conclusion
In Python, the keyboard module interacts with keyboard shortcuts and keys. It is easy to use. It is used in game development, automation tasks, and other applications. You can easily simulate key presses, register hotkeys, hook global events, and perform various actions. You can make games, automate tedious chores, and design unique keyboard shortcuts.
Frequently Asked Questions (FAQs)
Q1: Can the keyboard module be used to simulate mouse actions?
Answer: No, as the name suggests, it is used only for the keyboard. You can use the PyAutoGUI module for mouse-related tasks.
Q2: Is it possible to create macros using the keyboard module?
Answer: Yes. You can record and replay keyboard events suitable for creating macros and sequences of keystrokes to automate repetitive tasks.
Q3: Can you use the keyboard module in headless environments and background processes?
Answer: Yes. You can utilize it in headless environments and background processes. But it would help if you handled that properly.
Recommended Articles
We hope that this EDUCBA information on “Python Keyboard Module” was beneficial to you. You can view EDUCBA’s recommended articles for more information.