1

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!
God-status
  • 141
  • 2
  • 14
  • 1
    This python script would be running on the sleeping computer? I would imagine this would be dependent on the OS and whatever hooks/events it has available for resuming from sleep. – JNevill Dec 13 '21 at 17:22
  • 2
    If this has to work in any OS, that's a very different solution than if it has to work in just one OS like Windows. Without knowing your requirements, I think this question is too open-ended, since the answer will differ greatly depending on what those requirements are. – Random Davis Dec 13 '21 at 17:23
  • Thank you @JNevill, you are right. I just updated the question with the version of Python I am running (3.10) and the OS version I am using (MacOSX 10.15.7) – God-status Dec 13 '21 at 17:25
  • Don't know if anyone has written a python wrapper for this, but you can interface with MacOS's API using Objective-C or Swift natively, and it seems like you want to do this: https://stackoverflow.com/questions/9247710/what-event-is-fired-when-mac-is-back-from-sleep – Ted Klein Bergman Dec 13 '21 at 17:28
  • Not going to put this as a duplicate since I'm a little out of my knowledge-area, but this question is very similar and there is good sounding suggestions, though they don't sound entirely pythonic, which isn't surprising since this functionality is very OS specific/centric https://stackoverflow.com/questions/13752070/detect-when-osx-sleeps-resumes-from-sleep – JNevill Dec 13 '21 at 17:29
  • 1
    Looks like there are terminal commands which could do this, which you could call and read the results from Python: https://stackoverflow.com/questions/39468539/osx-check-if-screen-is-sleep-or-awake-from-command-line – Random Davis Dec 13 '21 at 17:31
  • @JNevill that looks promising, unfortunately I have no experience with either Swift or Objective-C. – God-status Dec 13 '21 at 17:31
  • Note that MacOS can wake itself up to do housekeeping, so you may get a lot of false alerts depending on settings or what exactly you check for. – Max Dec 13 '21 at 19:00
  • That's a good point. I'll implement a system whereby it checks how long the computer has been awake for. – God-status Dec 13 '21 at 19:56

2 Answers2

1

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()
Andreas Florath
  • 4,418
  • 22
  • 32
  • Huh, do you have any idea if this would work? It's a very interesting idea, certainly creative xD. – God-status Dec 13 '21 at 19:58
  • Hey again, sorry to contact you here after 2 days, but I got you script working, and integrated it into the alert system and it works great (what a genius solution btw). However, I did run into the problem that @Max mentioned, whereby the computer occasionally wakes itself up, which triggers the alert. Can you think of a way to circumvent this? I will admit, I don't know much about what and how the computer wakes up to do "housekeeping". – God-status Dec 16 '21 at 15:14
  • no need to use the hard-drive... – nmz787 Dec 01 '22 at 08:21
0

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(".", "root\cimv2").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.

TheConfax
  • 144
  • 10