我希望制作一个计时器,可以在系统(Mac OS X Yosemite)开启时进行计数。我的想法是使用Python并监听睡眠和恢复信号,每当系统开启时增加一个计数器。然而,我没有找到太多关于如何实现这一点的信息。
以下是需要回答的问题:
以下是需要回答的问题:
- 是否可以用我详细说明的方法解决这个问题?
- 有更好的方法来解决这个问题吗?
这里有一个使用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()
(基于此文档)
uptime
和sysctl -a | grep sleeptime
来帮助这个过程。虽然这不是一个Python解决方案,但如果您想在程序的某些部分中使用Python,您总是可以调用它。 - BlackVegetable