Skip to content

Instantly share code, notes, and snippets.

@JulyIghor
Last active February 24, 2025 23:10
Show Gist options
  • Save JulyIghor/0fe05566013e60b1003ce31ba518f17e to your computer and use it in GitHub Desktop.
Save JulyIghor/0fe05566013e60b1003ce31ba518f17e to your computer and use it in GitHub Desktop.
Fix MacBook Sleep Issues by Stopping Karabiner-Elements on Lock and Restarting on Unlock

Fix MacBook Sleep Issues by Stopping Karabiner-Elements on Lock and Restarting on Unlock

Overview

Stopping Karabiner-Elements on lock and restarting it on unlock fixes sleep issues on MacBooks. This script effectively ensures that the system enters sleep mode properly instead of staying active due to Karabiner’s background processes.

Prerequisites

Ensure you have PyObjC installed, as it is required to handle macOS system events.

pip3 install pyobjc

Script

Save the following script as karabiner_sleep_fix.py and make it executable:

#!/usr/bin/env python3
# MIT License Copyright (c) Ihor July https://gist.github.com/JulyIghor/0fe05566013e60b1003ce31ba518f17e

from Foundation import NSDistributedNotificationCenter, NSObject, NSRunLoop
import subprocess
import signal
import sys

class ScreenObserver(NSObject):
    def screenLocked_(self, notification):
        print("Screen locked – force stopping Karabiner-Elements...")
        for _ in range(3):
            subprocess.call([
                "killall", "-9", 
                "karabiner_console_user_server", 
                "Karabiner-Elements", 
                "Karabiner-Menu", 
                "Karabiner-NotificationWindow"
            ])

    def screenUnlocked_(self, notification):
        print("Screen unlocked – starting Karabiner-Elements...")
        subprocess.call([
            "/Library/Application Support/org.pqrs/Karabiner-Elements/bin/karabiner_console_user_server"
        ])

def handle_sigint(signal, frame):
    """Gracefully handle Ctrl+C"""
    print("\nStopping script...")
    sys.exit(0)

# Register Ctrl+C handler
signal.signal(signal.SIGINT, handle_sigint)

# Set up event listener
observer = ScreenObserver.alloc().init()
center = NSDistributedNotificationCenter.defaultCenter()
center.addObserver_selector_name_object_(observer, b"screenLocked:", "com.apple.screenIsLocked", None)
center.addObserver_selector_name_object_(observer, b"screenUnlocked:", "com.apple.screenIsUnlocked", None)

print("Listening for screen lock/unlock events... (Press Ctrl+C to stop)")

# Keep the script running while handling Ctrl+C properly
try:
    while True:
        NSRunLoop.currentRunLoop().runMode_beforeDate_("NSDefaultRunLoopMode", None)
except KeyboardInterrupt:
    handle_sigint(None, None)

How to Use

  1. Save the script as karabiner_sleep_fix.py.
  2. Make it executable:
    chmod +x karabiner_sleep_fix.py
  3. Run it:
    ./karabiner_sleep_fix.py

Expected Behavior

  • When the MacBook locks, Karabiner-Elements will be stopped.
  • When the MacBook unlocks, Karabiner-Elements will be restarted without opening the settings window.
  • The script will automatically fix sleep issues caused by Karabiner-Elements.

License

MIT License

Copyright Ihor July

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment