Skip to content

Instantly share code, notes, and snippets.

@scivision
Last active September 22, 2025 03:29
Show Gist options
  • Save scivision/d0e6dbebb88687791129ad722c90e68a to your computer and use it in GitHub Desktop.
Save scivision/d0e6dbebb88687791129ad722c90e68a to your computer and use it in GitHub Desktop.
inhibit Windows from suspend/sleep while subprocess is running
[flake8]
max-line-length = 100

Run program while preventing system sleep

It is a common problem that long-running programs are interrupted by the system going to sleep. Examples that benefit from caffeinate.py across operating systems include:

  • "rsync" or "scp" remote file transfers
  • long-running computations / simulations
  • "ffmpeg" video processing
  • CMake / Ninja / Make builds of large projects

This Python utility caffeinate.py runs a program while preventing the system from going to sleep. It works on Windows, macOS and Linux.

One can find several prior Python attempts going back over 10 years, but they typically aren't for calling a specific program and then automatically reallowing sleep when the program finishes, even if the called program crashes or errors. They also tend to be platform-specific.

Windows

Verify operation of caffeinate.py using SetThreadExecutionState on Windows by opening a second terminal as Administrator and check:

powercfg /requests

before, during and after running a command with caffeinate.py.

Note: WSL (Windows Subsystem for Linux) might not be able to prevent sleep on Windows, even when systemd-inhibit is available in the WSL environment. If this is an issue, run the command directly in Windows Command Prompt or PowerShell by invoking python3 caffeinate.py wsl.exe <command> <args> from the Windows Terminal.

macOS

caffeinate.py uses the macOS factory built-in caffeinate command. Verify operation of caffeinate.py on macOS by opening a second terminal and check

pmset -g assertions

Linux

On Linux, caffeinate.py uses the built-in systemd-inhibit command if available. Verify operation of caffeinate.py on Linux by opening a second terminal and check:

systemd-inhibit --list
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.10"
# ///
"""
Prevent the computer (macOS, Windows, Linux) from sleeping while subprocess runs
* Linux: assumes systemd-inhibit is available
* macOS: uses caffeinate command
* Windows: uses SetThreadExecutionState API via ctypes
Usage:
python caffeinate.py <command_to_run> <command_args>
Example:
python caffeinate.py python long_running_script.py --arg1 val1
python caffeinate.py rsync -av /source/ /destination/
python caffeinate.py ninja -C build_dir
python caffeinate.py make -j8
python caffeinate.py cmake --build build_dir
python caffeinate.py ping localhost
"""
import sys
import shutil
import logging
import subprocess
import typing
from contextlib import contextmanager
@contextmanager
def prevent_sleep() -> typing.Generator[None, None, None]:
"""
A Windows context manager to prevent the system from sleeping
using the SetThreadExecutionState API.
"""
match sys.platform:
case "win32":
import ctypes
ES_CONTINUOUS = 0x80000000
ES_SYSTEM_REQUIRED = 0x00000001
# Inhibit sleep
ctypes.windll.kernel32.SetThreadExecutionState(
ES_CONTINUOUS | ES_SYSTEM_REQUIRED
)
try:
yield
finally:
# Allow sleep again
ctypes.windll.kernel32.SetThreadExecutionState(ES_CONTINUOUS)
print("Execution finished. System sleep is now allowed.")
case ["darwin", "linux"]:
yield
case _:
logging.error(f"{sys.platform}: Sleep inhibition is not supported.")
yield
def main():
if len(sys.argv) < 2:
raise SystemExit(f"Usage: python {sys.argv[0]} <command_to_run> <command_args>")
command = sys.argv[1:]
# Platform-specific command wrapping
match sys.platform:
case "darwin":
command.insert(0, "caffeinate")
case "linux":
if shutil.which("systemd-inhibit"):
command.insert(0, "systemd-inhibit")
else:
logging.error("'systemd-inhibit' not found. System may sleep during execution.")
try:
with prevent_sleep():
subprocess.run(command, check=True)
except FileNotFoundError:
raise SystemExit(f"Error: Command '{command[0]}' not found.")
except subprocess.CalledProcessError as e:
raise SystemExit(f"Command failed with exit code {e.returncode}")
except KeyboardInterrupt:
raise SystemExit("\nProcess interrupted by user.")
if __name__ == "__main__":
main()
The MIT License (MIT)
Copyright © 2025 SciVision, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[tool.black]
line-length = 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment