Eric Bergman-Terrell's Blog

Python Programming Tip: Prevent Sleep when Running on Windows
February 6, 2021

I've written a file sync and verify program in Python. When the volume of files is large, there's a risk that my Windows machine will go into sleep mode before the program finishes. In order to prevent this, I include a call to PowerManagement.prevent_sleep() before the lengthy processing, and call PowerManagement.allow_sleep() afterwards (see source code, below).

In the past, I've written code to accomplish this by switching between Windows power plans.

Windows Power Plans

Unfortunately, there are some significant drawbacks to doing so:

The following code avoids these drawbacks by setting the program's thread execution state to values that will allow or prevent the OS from going into sleep mode:

import ctypes
import platform
from Globals import app_globals
from StringLiterals import StringLiterals


class PowerManagement:
    # https://trialstravails.blogspot.com/2017/03/preventing-windows-os-from-sleeping.html

    _ES_CONTINUOUS = 0x80000000
    _ES_SYSTEM_REQUIRED = 0x00000001

    @staticmethod
    def prevent_sleep():
        if platform.system() == StringLiterals.PLATFORM_WINDOWS:
            app_globals.log.print("Preventing Windows from going to sleep")
            ctypes.windll.kernel32.SetThreadExecutionState(
                PowerManagement._ES_CONTINUOUS | PowerManagement._ES_SYSTEM_REQUIRED)

    @staticmethod
    def allow_sleep():
        if platform.system() == StringLiterals.PLATFORM_WINDOWS:
            app_globals.log.print("Allowing Windows to go to sleep")
            ctypes.windll.kernel32.SetThreadExecutionState(PowerManagement._ES_CONTINUOUS)

The above source code is based on ideas from another developer. See the link in the comment.

Sleep
Sometimes it's just impossible to stay awake.

Complete source code available here.

Keywords: Python, Python 3, Windows, sleep, power plan, SetThreadExecutionState, ES_CONTINUOUS, ES_SYSTEM_REQUIRED

Reader Comments

Comment on this Blog Post

Recent Posts

TitleDate
Vault 3 Source Code in GitHubMarch 3, 2021
Vault 3 (Desktop) Version 0.70 ReleasedFebruary 27, 2021
Vault 3 (Desktop) Version 0.68 ReleasedFebruary 17, 2021
Python Programming Tip: Generate Hash for a FileFebruary 14, 2021
Python Programming Tip: Implement Retries with EaseFebruary 6, 2021
Python Programming Tip: Map Windows Volume Label to Corresponding Drive LetterFebruary 6, 2021
Python Programming Tip: Prevent Sleep when Running on WindowsFebruary 6, 2021