Prevent sleep mode python (Wakelock on python)

Max Dev picture Max Dev · Aug 25, 2019 · Viewed 11.8k times · Source

How I can prevent sleep-mode on python without using extra apps on different OS(Ubuntu, Windows...) but in most cases I need Linux solution

I am making app that works big amount of time. It uses like 80% of CPU, so a user just start this app and go away from keyboard. So I think I need something like system api or library that lock sleep-mode. I am sure that, it exists. For example, if you open any video player on your OS, your (PC, Laptop) will not go to sleep mode, the same thing in browser.

Also, there is the same thing in Android (WakeLock) or Windows (SetThreadExecutionState)

Answer

mishsx picture mishsx · Aug 25, 2019

I ran into similar situation where a process took long enough to execute itself that windows would hibernate. To overcome this problem I wrote a script.

The following simple piece of code can prevent this problem. When used, it will ask windows not to sleep while the script runs. (In some cases, such as when the battery is running out, Windows will ignore your request.)

    class WindowsInhibitor:
        '''Prevent OS sleep/hibernate in windows; code from:
        https://github.com/h3llrais3r/Deluge-PreventSuspendPlus/blob/master/preventsuspendplus/core.py
        API documentation:
        https://msdn.microsoft.com/en-us/library/windows/desktop/aa373208(v=vs.85).aspx'''
        ES_CONTINUOUS = 0x80000000
        ES_SYSTEM_REQUIRED = 0x00000001

        def __init__(self):
            pass

        def inhibit(self):
            import ctypes
            print("Preventing Windows from going to sleep")
            ctypes.windll.kernel32.SetThreadExecutionState(
                WindowsInhibitor.ES_CONTINUOUS | \
                WindowsInhibitor.ES_SYSTEM_REQUIRED)

        def uninhibit(self):
            import ctypes
            print("Allowing Windows to go to sleep")
            ctypes.windll.kernel32.SetThreadExecutionState(
                WindowsInhibitor.ES_CONTINUOUS)

To run the script, simply :

    import os

    osSleep = None
    # in Windows, prevent the OS from sleeping while we run
    if os.name == 'nt':
        osSleep = WindowsInhibitor()
        osSleep.inhibit()

    # do slow stuff

    if osSleep:
        osSleep.uninhibit()