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.
Ensure you have PyObjC installed, as it is required to handle macOS system events.
pip3 install pyobjc
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)
- Save the script as
karabiner_sleep_fix.py
. - Make it executable:
chmod +x karabiner_sleep_fix.py
- Run it:
./karabiner_sleep_fix.py
- 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.
MIT License
Copyright Ihor July