Skip to content

Instantly share code, notes, and snippets.

@kbarnes3
Forked from jonasbits/keepawake.py
Created December 29, 2014 04:30
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save kbarnes3/3fb7d353e9bdd3efccd5 to your computer and use it in GitHub Desktop.
Save kbarnes3/3fb7d353e9bdd3efccd5 to your computer and use it in GitHub Desktop.
# This file provides a long_running decorator to indicate that a function needs a long amount of time to complete and
# the computer should not enter standby. This file currently only works on Windows and is a no-op on other platforms.
import ctypes
import platform
ES_CONTINUOUS = 0x80000000
ES_SYSTEM_REQUIRED = 0x00000001
def _set_thread_execution(state):
ctypes.windll.kernel32.SetThreadExecutionState(state)
def prevent_standby():
if platform.system() == 'Windows':
_set_thread_execution(ES_CONTINUOUS | ES_SYSTEM_REQUIRED)
def allow_standby():
if platform.system() == 'Windows':
_set_thread_execution(ES_CONTINUOUS)
def long_running(func):
def inner(*args, **kwargs):
prevent_standby()
result = func(*args, **kwargs)
allow_standby()
return result
return inner
@connectedbit
Copy link

Works great on Windows 10, but doesn't work on Windows 11.

@kbarnes3
Copy link
Author

kbarnes3 commented Oct 9, 2022

I don't actually use this anymore to confirm, but a quick test has Windows say it is working correctly. I'm verifying this with the initial release of Windows 11 and Python 3.10.7. After calling prevent_standby() in a Python console, I ran powercfg -requests as an admin in another terminal. It outputs:

DISPLAY:
None.

SYSTEM:
[PROCESS] \Device\HarddiskVolume5\Program Files\Python310\python.exe

AWAYMODE:
None.

EXECUTION:
None.

PERFBOOST:
None.

ACTIVELOCKSCREEN:
None.

Which indicates Windows thinks it shouldn't go to sleep even if idle. Running allow_standby() or quitting Python clears the Python.exe entry from the system section.

What behavior are you seeing?

@connectedbit
Copy link

Sorry. My mistake. Just confirmed it is working in Windows 11.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment