Friday, March 10, 2017

Preventing Windows OS from sleeping while your python code runs

Do you have a python script that you want to run through to completion, but might take several hours without user interaction?

Might you run on a laptop or other Windows computer that has power management enabled, so that it might go to sleep or hibernate when not being used?

If you do nothing, windows will likely sleep or hibernate before your script can complete.

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 it, 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()

It is based on code from here, which also has code for preventing suspension on Linux under GNOME and KDE, should you need that.

6 comments:

  1. Really appreciated the information and please keep sharing, I would like to share some information regarding online training.Maxmunus Solutions is providing the best quality of this PYTHON programming language. and the training will be online and very convenient for the learner.This course gives you the knowledge you need to achieve success.

    For Joining online training batches please feel free to call or email us.
    Email : minati@maxmunus.com
    Contact No.-+91-9066638196/91-9738075708
    website:-http://www.maxmunus.com/page/Python-Training

    ReplyDelete
  2. Hello, thanks for this code, do you know if this code will keep Windows awake forever? I wanted to use this code in some kind of 'scheduler', but Windows went in sleep mode after a few hours. Thanks for your return.

    ReplyDelete
    Replies
    1. My understanding is that Windows takes it as a suggestion. It may override your request. But I'm not sure under which conditions, apart from if you are running out of battery.

      Delete
  3. This comment has been removed by the author.

    ReplyDelete