Is there a way to detect if a computer is brought out of sleep mode?

Question:

Problem

I want to write a program in Python, where a script executes when it detects that it has been brought out of sleep mode.
E.g I am using a laptop. When I open the laptop, the script should run. Is there a way to detect this and then run a script? Is there a module for listening for such events?


Goal

The ultimate goal is a sort of security system, where an alert is sent to a users phone, if their computer is used. I have an idea for the alert sending part, I just can’t figure out how to trigger the program in the first place.

The basic format should look something like this:
if computer_active == True:
    alert.send("Computer accessed")
    

Obviously it would look more complicated than that, but that’s the general idea.

I’m running Python3.10.0 on MacOSX v10.15.7

Any help is greatly appreciated!
Asked By: God-status

||

Answers:

A maybe-better-than-nothing-solution. It’s hacky, it needs to run always, it’s not event driven; but: it’s short, it’s configurable and it’s portable 🙂

'''
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()
Answered By: Andreas Florath

Question is old, but since I was looking for the same thing and I did not find anything on the web…

import win32com.client

colMonitoredEvents = win32com.client.Dispatch("WbemScripting.SWbemLocator").ConnectServer(".", "rootcimv2").ExecNotificationQuery("Select * from Win32_PowerManagementEvent")

while True:
    objLatestEvent = colMonitoredEvents.NextEvent()
    if objLatestEvent.EventType == 7:
        pass #do your stuff here

Event based, run it indefinitely with low CPU usage and do stuff when the event ID is 7; event 4 should be catched instead when entering sleep. Note that with event 4 the action should be very quick or likely it will not complete before the PC goes to sleep.

Answered By: TheConfax
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.