pythonwinreg

How to handle PermissionError when changing registry value using Python


I am trying to code a program in python to change a windows computer to dark mode if it is in light mode, or vice versa. However, when I run the code, it the I get a response: "PermissionError: [WinError 5] Access is denied." Can anyone help me? Also, this is my first time playing with registries, so I recognize this code could be extremely inefficient.

import winreg
# goes to correct directory in registry
with winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER) as hkey:
    with winreg.OpenKey(hkey, "SOFTWARE") as hkey2:
        with winreg.OpenKey(hkey2, "Microsoft") as hkey3:
            with winreg.OpenKey(hkey3, "Windows") as hkey4:
                with winreg.OpenKey(hkey4, "CurrentVersion") as hkey5:
                    with winreg.OpenKey(hkey5, "Themes") as hkey6:
                        with winreg.OpenKey(hkey6, "Personalize") as hkey7:
                            # checks if windows is using dark or light mode
                            answer = winreg.QueryValueEx(hkey7, "AppsUseLightTheme")
                            value = answer[0]
                            if value == 0:
                                insert = 1
                            elif value == 1:
                                insert = 0
                            # sets windows to dark or light mode, opposite of what it was before
                            winreg.SetValueEx(hkey7, "AppsUseLightTheme", 0, 4, insert)
                            print(value)
                            print(insert)
                            input()

Solution

  • As the docs state, winreg.OpenKey defaults to access=KEY_READ. As a side note, you can do all those subkeys in one shot:

        with winreg.OpenKey(hKey, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", access=winreg.KEY_READ|winreg.KEY_WRITE) as hkey2: