如何最好地抓住睡眠并恢复OSX的活动?

时间:2015-06-27 17:19:20

标签: python macos bash osx-yosemite

我想制作一个计时器,只要系统(Mac OS X Yosemite)打开就会计时。我的想法是使用python并监听睡眠和恢复信号,并在系统启动时递增计数器。但是,我还没有找到关于如何做到这一点的更多信息。

  1. 用我详细说明的问题解决这个问题是否可行?
  2. 有没有更好的方法来解决这个问题?
  3. 谢谢!

1 个答案:

答案 0 :(得分:0)

以下是使用PyObjC的示例(默认情况下应该在Yosemite上安装,或者可能在安装Xcode之后安装):

#!/usr/bin/env python

from AppKit import NSWorkspace, NSWorkspaceWillSleepNotification, \
                   NSWorkspaceDidWakeNotification, NSObject, \
                   NSApplication, NSLog

class App(NSObject):

    def applicationDidFinishLaunching_(self, notification):
        workspace          = NSWorkspace.sharedWorkspace()
        notificationCenter = workspace.notificationCenter()
        notificationCenter.addObserver_selector_name_object_(
            self,
            self.receiveSleepNotification_,
            NSWorkspaceWillSleepNotification,
            None
        )
        notificationCenter.addObserver_selector_name_object_(
            self,
            self.receiveWakeNotification_,
            NSWorkspaceDidWakeNotification,
            None
        )

    def receiveSleepNotification_(self, notification):
        NSLog("receiveSleepNotification: %@", notification)

    def receiveWakeNotification_(self, notification):
        NSLog("receiveWakeNotification: %@", notification)

if __name__ == '__main__':
    sharedapp = NSApplication.sharedApplication()
    app       = App.alloc().init()
    sharedapp.setDelegate_(app)
    sharedapp.run()

(基于this document