Last active
January 30, 2026 01:57
-
-
Save io-mi/764cd8623334a38d70e8ce9960161c59 to your computer and use it in GitHub Desktop.
Python OpenGL select GPU
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import sys | |
| from enum import IntEnum | |
| class PreferredGPU(IntEnum): | |
| AUTO = 0 | |
| POWER_SAVING = 1 | |
| HIGH_PERFORMANCE = 2 | |
| if sys.platform == "win32": | |
| import winreg | |
| class GPUPreference: | |
| _KEY_PATH = "SOFTWARE\\Microsoft\\DirectX\\UserGpuPreferences" | |
| _EXE_PATH = sys.base_prefix + "\\python.exe" | |
| def __init__(self, preference:PreferredGPU) -> None: | |
| self._preference = preference | |
| self._prev_value = None | |
| def __enter__(self) -> None: | |
| try: | |
| with winreg.OpenKey(winreg.HKEY_CURRENT_USER, self._KEY_PATH, 0, winreg.KEY_READ) as key: | |
| self._prev_value, _ = winreg.QueryValueEx(key, self._EXE_PATH) | |
| except (FileNotFoundError, OSError): | |
| self._prev_value = None | |
| with winreg.CreateKey(winreg.HKEY_CURRENT_USER, self._KEY_PATH) as key: | |
| winreg.SetValueEx(key, self._EXE_PATH, 0, winreg.REG_SZ, "GpuPreference={0};".format(self._preference.value)) | |
| def __exit__(self, exc_type, exc_value, exc_traceback) -> None: | |
| with winreg.OpenKey(winreg.HKEY_CURRENT_USER, self._KEY_PATH, 0, winreg.KEY_SET_VALUE) as key: | |
| if self._prev_value is None: | |
| try: | |
| winreg.DeleteValue(key, self._EXE_PATH) | |
| except (FileNotFoundError, OSError): | |
| pass | |
| else: | |
| winreg.SetValueEx(key, self._EXE_PATH, 0, winreg.REG_SZ, self._prev_value) | |
| else: | |
| class GPUPreference: | |
| def __init__(self, *_, **__): | |
| raise NotImplementedError("GPUPreference is only supported on Windows") | |
| # TEST | |
| import glfw | |
| from OpenGL.GL import * | |
| if __name__ == "__main__": | |
| with GPUPreference(PreferredGPU.HIGH_PERFORMANCE): | |
| glfw.init() | |
| glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3) | |
| glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3) | |
| glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE) | |
| glfw.make_context_current( | |
| glfw.create_window(1920, 1080, "GPU preference", None, None)) | |
| print(glGetString(GL_VENDOR).decode()) | |
| print(glGetString(GL_RENDERER).decode()) | |
| print(glGetString(GL_VERSION).decode()) | |
| print("-"*32) | |
| glfw.terminate() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment