How to Blink Caps Lock Key using Python Code

Introduction

When you hit the caps lock key, you usually see a light on your keyboard blinking on and off, right? Well, let’s do something cool with it! In this tutorial, I’ll show you how to make that caps lock light blink using a Python program. You can scare your friends easily with this keyboard automation trick.

In the code, I’ve set it up so the light blinks a certain number of times. But hey, feel free to change that number however you like!

The topic of this tutorial shows the diversity of Python programming language and its features. The article is made for educational purposes and doesn’t promote or encourage any unethical intent.

The Author (Subhankar Rakshit)

Requirements

Make sure Python is installed on your system. If not, don’t worry, grab the latest version from their website (https://www.python.org/). Once settled, remember to install pynput and python-xlib using the commands below.

pip install pynput
pip install python-xlib

The Python Program

import time
from Xlib import display
from pynput.keyboard import Key, Controller

count = 0
# Total number of times caps lock key should blink
blink_count = 40

def light_control():
    global count
    # Creating a Controller object
    keyboard = Controller()
    time.sleep(0.3)

    # Establishing connection with X server
    DISPLAY = display.Display()
    keyb = DISPLAY.get_keyboard_control()
    # Extracting data about keyboard state
    DATA = keyb._data
    # Extracting LED mask which includes caps lock state
    led = DATA['led_mask']
    
    # Checking if caps lock is currently on
    caps= (led & 1) == 1

    if count < blink_count:
        # Caps On
        if caps:
            keyboard.press(Key.caps_lock)
            keyboard.release(Key.caps_lock)
            print('Caps is OFF')
        # Caps Off
        else:
            keyboard.press(Key.caps_lock)
            keyboard.release(Key.caps_lock)
            print("Caps is ON")

        count += 1
        # Recursive call to continue toggling caps lock
        light_control()

light_control()

In the code above, the Caps Lock LED blinks on and off a total of 40 times. Feel free to customize this number by adjusting the value in the ‘blink_count‘ variable.

Output

Automating the Caps Lock key is a funny trick that showcases your coding skills! It’s perfect for pranks or to show your creative programming skills. For more programming examples like this, visit our separate page packed with Cool Python Programs.

Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! I’m Subhankar Rakshit, the brains behind PySeek. I’m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles: 194