【问题标题】:How to best catch sleep and resume events for OSX?如何最好地捕捉 OSX 的睡眠和恢复事件?
【发布时间】:2015-09-14 11:36:54
【问题描述】:

我想制作一个在系统 (Mac OS X Yosemite) 开启时计数的计时器。我的想法是使用 python 并监听睡眠和恢复信号,并在系统开启时增加一个计数器。但是,我无法找到有关如何执行此操作的太多信息。

  1. 用我详细介绍的内容来解决这个问题是否可行?
  2. 有没有更好的方法来解决这个问题?

谢谢!

【问题讨论】:

  • 查看uptimesysctl -a | grep sleeptime 以帮助完成此过程。它不是一个 python 解决方案,但如果你想在程序的某些部分使用 python,你可以随时使用它。

标签: python macos bash osx-yosemite


【解决方案1】:

这是一个使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 2012-07-19
    • 1970-01-01
    • 2012-03-04
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多