Skip to content

Instantly share code, notes, and snippets.

@hardenchant
Last active April 26, 2022 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hardenchant/a0890ea292d38d77afc9c797852b2c5c to your computer and use it in GitHub Desktop.
Save hardenchant/a0890ea292d38d77afc9c797852b2c5c to your computer and use it in GitHub Desktop.
Run action when mac unlock
import logging
import os
# pip install pyobjc
from AppKit import NSDate, NSDistributedNotificationCenter, NSObject, NSRunLoop
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s] %(levelname)s [%(funcName)s:%(lineno)d] %(message)s"
)
class NotificationHandler(NSObject):
def init(self):
self = super(NotificationHandler, self).init()
if self is None:
return None
self.dnc = NSDistributedNotificationCenter.defaultCenter()
self.dnc.addObserver_selector_name_object_(self, 'didWakeNotification:', 'com.apple.screenIsUnlocked', None)
return self
def __del__(self):
self.dnc.removeObserver_(self)
def didWakeNotification_(self, notification):
# sudo required
os.system('killall mDNSResponder')
logging.info('mDNSResponder was killed')
def main():
# not used, but require save the link to obj for work
notification_handler = NotificationHandler.alloc().init() # noqa
while True:
NSRunLoop.currentRunLoop().runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.1))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment