2015-06-27 56 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