如何解决使用 Python 更改注册表值时如何处理 PermissionError
我正在尝试在 python 中编写一个程序,如果它处于亮模式,则将 Windows 计算机更改为暗模式,反之亦然。但是,当我运行代码时,我得到一个响应:“PermissionError: [WinError 5] Access is denied。”谁能帮我?此外,这是我第一次使用注册表,所以我意识到这段代码可能非常低效。
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",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:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。