[Pythonmac-SIG] [py-appscript] is System Events sleeping ?

Karsten Wolf karstenwo at googlemail.com
Wed Feb 2 01:22:51 CET 2011

Am 30.01.2011 um 16:12 schrieb Fandekasp:

> Ok so the only solution for me is to map a sleep key which will  
> call my
> program and plan some tasks (threading.Timer), and my program will  
> force my
> system to sleep after that.

If you're willing to dive into pyobjc, NSWorkspace may help you.

Ask for a NSWorkspaceWillSleepNotification and you get ca. 30 seconds  
to finish your pre-sleep duties, after that, well you're asleep.

This is a modified script from the pyobjc examples and works on  
python 2.7 with pyobjc 1.4 on OSX 10.4. YMMV.


P.S.: There are many more notifications. Application launch/quit;  
volumes mount/unmount; sleep, wake, power-off. The original demo ran  
a script when a new volume was mounted. Read the NSWorkspace class  

#!/usr/bin/env python

import time

import Foundation
NSObject = Foundation.NSObject

import AppKit
NSWorkspace = AppKit.NSWorkspace
NSWorkspaceWillSleepNotification =  
NSWorkspaceDidWakeNotification = AppKit.NSWorkspaceDidWakeNotification

import PyObjCTools.AppHelper as AppHelper

class NotificationHandler(NSObject):
     """Class that handles the sleep notifications."""

     def handleSleepNotification_(self, aNotification):
         for i in range(1, 101):
             print str(i)+u"seconds yet.."

ws = NSWorkspace.sharedWorkspace()
notificationCenter = ws.notificationCenter()
sleepHandler = NotificationHandler.new()

print "Waiting for sheep count to start..."

More information about the Pythonmac-SIG mailing list