How to create global keyboard shortcuts in Linux with Python
Learn how to intercept keyboard events in Linux using Python scripts without relying on heavy third-party desktop tools.
Summary
- Python scripts provide fine-grained control over Linux hardware input events.
- The X11 window server simplifies listening to global keystrokes using lightweight libraries.
- Wayland environments require evdev-based approaches to capture devices directly.
- Automating repetitive workflows eliminates friction on your desktop environment.
- Exception handling ensures the background script runs continuously without crashing.
Why build your own global shortcuts in Linux
Oftentimes, standard desktop environment managers do not offer enough flexibility for creating custom commands. When you need to trigger complex scripts or manage windows with specific key combinations, resorting to bloated third-party software can clutter your system. The ideal solution lies in writing small, customized scripts—much like automating server backups using Bash scripts—ensuring lightweight execution and absolute control over hardware behavior.
In practice, this means we can program the computer to respond instantly to any key combination, executing math functions, launching specific applications, or controlling media playback. The major benefit of this approach is independence from rigid graphical interfaces. You build a tailor-made tool for your daily workflow while consuming a minimal fraction of memory and CPU power.
Understanding X11 and Wayland background mechanics
Before writing any code, it is helpful to understand how Linux handles input devices. In traditional X11-based systems, the display server centralizes input events, allowing applications to listen to global keystrokes relatively easily. However, with the migration to Wayland, security was hardened to prevent one application from snooping on another, which blocks direct key monitoring by standard programs.
To bypass this security restriction without resorting to heavy software, developers access kernel input device files directly via the library or by manipulating the Linux event subsystem known as . This versatility allows scripts to run smoothly on both legacy stations and modern environments, ensuring your automation works regardless of your distribution.
Preparing the environment and installing essential libraries
To get started, we will use Python combined with a library focused on input device control. Ensure Python is installed on your system and use the pip package manager to download the required library. The process is straightforward, requiring only basic permissions to read hardware events for your current user.
Open your terminal and run the following command to install the package responsible for monitoring the keyboard. If you use Debian or Ubuntu-based distributions, you may need to install operating system development dependencies before proceeding with the pip installation.
sudo apt update && sudo apt install -y python3-pip python3-dev
pip3 install pynputWith the package properly installed, the Python interpreter gains the ability to register global keyboard listeners. This function runs in the background, listening to every key press or release, ready to trigger customized actions whenever the exact combination is identified by the algorithm.
Writing the Python script to intercept keys
Now that the environment is ready, let's create a structured script that monitors specific keys and executes operating system commands. The code below uses the library to capture the exact moment a key combination is pressed. The logic checks whether modifier keys, such as Ctrl or the Super key, are active simultaneously with a specific letter.
Create a file named shortcuts.py in your home directory and paste the functional code below. It monitors the key combination to open a terminal or execute a custom command in a fully automated and crash-free manner.
from pynput import keyboard
import subprocess
# Define the desired key combination
COMBINATION = {keyboard.Key.ctrl, keyboard.Key.alt, keyboard.KeyCode(char=\'t\')}
# Set to track currently pressed keys
current_keys = set()
def on_press(key):
if key in COMBINATION:
current_keys.add(key)
if all(k in current_keys for k in COMBINATION):
# Run the desired system command
subprocess.Popen([\'gnome-terminal\'])
def on_release(key):
try:
current_keys.remove(key)
except KeyError:
pass
# Start the global listener
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()This script runs continuously, intercepting hardware events in an elegant way. Using the module ensures that external commands are fired asynchronously, preventing the keyboard listener from experiencing delays or stutters while the operating system launches the requested window.
Running the script in the background with system services
Keeping the script running only in a terminal window is impractical for daily use. To turn your automation into a persistent service that starts alongside the operating system, the best practice in Linux is to create a user systemd service unit file.
Create the services directory if it does not exist yet and configure the initialization file for your Python script. This ensures the system restarts the script if any technical glitch occurs, keeping your global shortcuts always available and functional on your desktop.
mkdir -p ~/.config/systemd/user/
nano ~/.config/systemd/user/my-shortcuts.serviceInside the newly created file, add the configuration directives pointing to the absolute path where your Python script is saved. Next, enable and start the service using the systemd manager with the appropriate commands for your current user.
[Unit]
Description=Python Global Shortcuts Service
After=graphical.target
[Service]
ExecStart=/usr/bin/python3 /home/user/shortcuts.py
Restart=always
[Install]
WantedBy=graphical-session.targetSave the file and run systemctl --user daemon-reload followed by systemctl --user enable --now my-shortcuts.service in your terminal. This way, your shortcuts remain permanently active, offering a massive productivity boost without consuming excessive hardware resources.
Final thoughts
Building your own global keyboard shortcuts using Python and lightweight Linux libraries removes the need for bloated, complex software. This approach puts customization power directly into your hands, allowing you to tailor your desktop environment precisely to your daily operational needs. Mastering these basic event-handling techniques opens the door to automating any routine and making your operating system experience much smoother and more efficient.