使用python检查注册表项是否存在
-
21-12-2019 - |
题
我正在寻找一种方法来检查 python 中是否存在注册表项。
我该如何执行此操作或需要什么代码来检查注册表项是否存在?
解决方案
在之前的答案中似乎是一些信息这里
from _winreg import *
key_to_read = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'
try:
reg = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
k = OpenKey(reg, key_to_read)
# do things with the key here ...
except:
# do things to handle the exception here
. 其他提示
这是一篇较旧的文章,但经过一些类似的搜索后,我觉得我应该向其中添加一些信息。 winreg
,据我所知,仅适用于 Windows 环境。 python 注册表 经过 威利巴伦辛 可以用于跨平台执行此操作,并且在使用注册表时有许多不错的选项。
如果您的目标键包含要提取的值,您可以按照以下步骤列出它们......首先,导入模块(pip install python-registry)。这可能不起作用,因为主文件夹被插入到 libs/sitepackages 中,请确保 登记处 文件夹位于站点包的根目录下。
from Registry import Registry # Ensure Registry is in your libs/site-packages
接下来创建您的函数并确保添加 try:
和 except
进入你的函数来检查它是否存在。
# Store internal Registry paths as variable, may make it easier, remove repeating yourself
time_zone = "ControlSet001\\Control\\TimeZoneInformation"
# STORE the path to your files if you plan on repeating this process.
<Path_To_reg_hive> = "C:\\Users\\Desktop\\Whatever_Folder\\SYSTEM"
def get_data():
registry = Registry.Registry(<Path_To_reg_hive>) # Explicitly, or use variable above
try:
key = registry.open(time_zone) # Registry.Registry opens reg file, goes to the path (time_zone)
except Registry.RegistryKeyNotFoundException: # This error occurs if Path is not present
print("Sorry Bud, no key values found at : " + time_zone) # If not there, print a response
您可以对要检查的所有内容创建一个字典,然后通过此过程迭代它以一次检查多个,或一次仅检查一个。这是一个工作示例:
from Registry import Registry
# These can be included directly into the function, or separated if you have several
system = "SYSTEM" # or a Path, I have a SYSTEM hive file in my working environment folder
time_zone = "ControlSet001\\Control\\TimeZoneInformation123" # Path you want to check, added 123 so its not there
def get_data():
registry = Registry.Registry(system) # Explicitly, or use variable above
try:
key = registry.open(time_zone) # Registry.Registry opens reg file, goes to the path (time_zone)
except Registry.RegistryKeyNotFoundException: # This error occurs if Path is not present
print("Sorry Bud, no key values found at : " + time_zone) # If not there, print a response
# key is identified above only to use later, such as.... for v in key.subkeys(): Do more stuff
get_data()
返回,
Sorry Bud, no key values found at : ControlSet001\Control\TimeZoneInformation123
不隶属于 StackOverflow