Search code examples
pythonpython-3.xsystem

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


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!

Solution

  • 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()