有没有办法检测计算机是否退出睡眠模式?
Is there a way to detect if a computer is brought out of sleep mode?
问题
我想在 Python 中编写一个程序,其中一个脚本在检测到它已退出睡眠模式时执行。
例如,我正在使用笔记本电脑。当我打开笔记本电脑时,脚本应该 运行。有没有办法检测到这一点,然后 运行 一个脚本?是否有监听此类事件的模块?
目标
最终目标是一种安全系统,如果用户 phone 使用了他们的计算机,就会向其发送警报。我对警报发送部分有一个想法,我只是不知道如何首先触发该程序。
基本格式应如下所示:
if computer_active == True:
alert.send("Computer accessed")
显然它看起来会比这更复杂,但这是一般的想法。
我在 MacOSX v10.15.7
上 运行ning Python3.10.0
非常感谢任何帮助!
一个也许比什么都没有的解决方案。它很老套,它需要始终 运行,它不是事件驱动的;但是:它很短,它是可配置的,而且是可移植的:-)
'''
Idea: write every some seconds to a file and check regularly.
It is assumed that if the time delta is too big,
the computer just woke from sleep.
'''
import time
TSFILE="/tmp/lastts"
CHECK_INTERVAL=15
CHECK_DELTA = 7
def wake_up_from_sleep():
print("Do something")
def main():
while True:
curtime = time.time()
with open(TSFILE, "w") as fd:
fd.write("%d" % curtime)
time.sleep(CHECK_INTERVAL)
with open(TSFILE, "r") as fd:
old_ts = float(fd.read())
curtime = time.time()
if old_ts + CHECK_DELTA < curtime:
wake_up_from_sleep()
if __name__ == '__main__':
main()
问题
我想在 Python 中编写一个程序,其中一个脚本在检测到它已退出睡眠模式时执行。 例如,我正在使用笔记本电脑。当我打开笔记本电脑时,脚本应该 运行。有没有办法检测到这一点,然后 运行 一个脚本?是否有监听此类事件的模块?
目标
最终目标是一种安全系统,如果用户 phone 使用了他们的计算机,就会向其发送警报。我对警报发送部分有一个想法,我只是不知道如何首先触发该程序。
基本格式应如下所示:
if computer_active == True:
alert.send("Computer accessed")
显然它看起来会比这更复杂,但这是一般的想法。
我在 MacOSX v10.15.7
上 运行ning Python3.10.0非常感谢任何帮助!
一个也许比什么都没有的解决方案。它很老套,它需要始终 运行,它不是事件驱动的;但是:它很短,它是可配置的,而且是可移植的:-)
'''
Idea: write every some seconds to a file and check regularly.
It is assumed that if the time delta is too big,
the computer just woke from sleep.
'''
import time
TSFILE="/tmp/lastts"
CHECK_INTERVAL=15
CHECK_DELTA = 7
def wake_up_from_sleep():
print("Do something")
def main():
while True:
curtime = time.time()
with open(TSFILE, "w") as fd:
fd.write("%d" % curtime)
time.sleep(CHECK_INTERVAL)
with open(TSFILE, "r") as fd:
old_ts = float(fd.read())
curtime = time.time()
if old_ts + CHECK_DELTA < curtime:
wake_up_from_sleep()
if __name__ == '__main__':
main()