使用 Python 更改注册表值时如何处理 PermissionError

How to handle PermissionError when changing registry value using Python

我正在尝试在 python 中编写一个程序,以便将 windows 计算机在亮模式下更改为暗模式,反之亦然。但是,当我 运行 代码时,我得到一个响应:“PermissionError:[WinError 5] 访问被拒绝。”谁能帮我?另外,这是我第一次玩注册表,所以我知道这段代码可能效率极低。

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()

如文档所述,winreg.OpenKey 默认为 access=KEY_READ。作为旁注,您可以一次完成所有这些子键:

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