Skip to content

Instantly share code, notes, and snippets.

@glyph
Created February 12, 2014 23:37
Show Gist options
  • Save glyph/8966828 to your computer and use it in GitHub Desktop.
Save glyph/8966828 to your computer and use it in GitHub Desktop.
onlock.py
from __future__ import print_function
import os, sys, pipes
import objc
from Foundation import NSObject
from CoreFoundation import (
CFRunLoopRun, CFRunLoopStop, CFFileDescriptorCreate,
CFFileDescriptorCreateRunLoopSource, CFRunLoopAddSource,
kCFRunLoopDefaultMode, CFRunLoopGetCurrent,
CFFileDescriptorEnableCallBacks, kCFFileDescriptorReadCallBack
)
from AppKit import NSNotificationCenter, NSDistributedNotificationCenter
class Locked(NSObject):
@objc.selectorFor(NSNotificationCenter.addObserver_selector_name_object_)
def observe_(self, notification):
command = ' '.join(map(pipes.quote, sys.argv[1:]))
print("Sleep: running ", command)
os.system(command)
nsdnc = NSDistributedNotificationCenter.defaultCenter()
nsdnc.addObserver_selector_name_object_(
Locked.alloc().init().retain(), "observe:", "com.apple.screenIsLocked",
None,
)
def handle_signals():
def stop(cffd, cbt, info):
CFRunLoopStop(CFRunLoopGetCurrent())
r, w = os.pipe()
cffd = CFFileDescriptorCreate(None, r, False, stop, None)
CFFileDescriptorEnableCallBacks(cffd, kCFFileDescriptorReadCallBack)
cfrlsrc = CFFileDescriptorCreateRunLoopSource(None, cffd, 0)
CFRunLoopAddSource(CFRunLoopGetCurrent(), cfrlsrc, kCFRunLoopDefaultMode)
def nop(signum, stackframe):
pass
import signal
signal.set_wakeup_fd(w)
signal.signal(signal.SIGINT, nop)
signal.signal(signal.SIGTERM, nop)
handle_signals()
CFRunLoopRun()
@mksh
Copy link

mksh commented Mar 19, 2014

:3

@r0ysue
Copy link

r0ysue commented Oct 7, 2017

Really helped me a lot!Thank you!

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