检查python是否存在注册表项

时间:2014-04-11 14:19:48

标签: python python-2.7 registry pywin32 registrykey

我正在寻找一种检查python是否存在注册表项的方法。

如何执行此操作或检查注册表项是否存在需要使用哪些代码?

2 个答案:

答案 0 :(得分:3)

以前的回答here中似乎有一些信息。

您是否要检查它的存在,因为您希望程序读取它?要检查它们是否存在键,可以将其包装在try-except块中。这将防止尝试读取密钥的“竞争条件”,在检查其存在和实际读取密钥之间修改的(不太可能的)事件中。类似的东西:

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

答案 1 :(得分:2)

这是一篇较旧的文章,但经过一些类似的搜索,我认为我会为此添加一些信息。根据我发现,winreg仅适用于Windows环境。 williballenthin python-registry可用于实现此跨平台,并且在与注册管理机构合作时有很多不错的选择。

如果您的目标键具有要提取的值,则可以按照以下步骤将其列出。...首先,导入模块(pip install python-registry)。由于主文件夹已插入libs / sitepackages中,因此这可能无法正常工作,请确保 Registry 文件夹位于站点软件包的根目录中。

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
相关问题