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
EBTCalc (Android) Version 1.53 is now availableMay 19, 2024
Vault 3 Security EnhancementsOctober 24, 2023
Vault 3 is now available for Apple OSX M2 Mac Computers!September 18, 2023
Vault (for Desktop) Version 0.77 ReleasedMarch 26, 2023
EBTCalc (Android) Version 1.44 is now availableOctober 12, 2021
Vault (Desktop) Version 0.72 ReleasedOctober 6, 2021
EBT Compass is Now Available for Android DevicesJune 2, 2021