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.
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.
Sometimes it's just impossible to stay awake.
Complete source code available here.
|Vault 3 Source Code in GitHub||March 3, 2021|
|Vault 3 (Desktop) Version 0.70 Released||February 27, 2021|
|Vault 3 (Desktop) Version 0.68 Released||February 17, 2021|
|Python Programming Tip: Generate Hash for a File||February 14, 2021|
|Python Programming Tip: Implement Retries with Ease||February 6, 2021|
|Python Programming Tip: Map Windows Volume Label to Corresponding Drive Letter||February 6, 2021|
|Python Programming Tip: Prevent Sleep when Running on Windows||February 6, 2021|