2015-06-27 54 views
3

我想制作一个计时器,每当系统(Mac OS X Yosemite)打开时计数一次。我的想法是使用python并收听睡眠并恢复信号,并在系统开启时增加计数器。但是,我一直无法找到关于如何做到这一点的很多信息。如何最好地捕捉OSX的睡眠和恢复事件?

  1. 以我所详述的方式解决这个问题是否可行?
  2. 有没有更好的方法来解决这个问题?

谢谢!

+0

退房'uptime'和'sysctl的 - a | grep sleeptime'来帮助完成这个过程。这不是一个python解决方案,但如果你想在你的程序的某些部分使用python的话,你总是可以掏出它。 – BlackVegetable

回答

0

下面是使用PyObjC(这应该是默认,或安装的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