使用python检查注册表项是否存在

使用python检查注册表项是否存在,python,python-2.7,registry,pywin32,registrykey,Python,Python 2.7,Registry,Pywin32,Registrykey,我正在寻找一种方法来检查python是否存在注册表项 如何执行此操作,或者需要什么代码来检查注册表项是否存在?前面的回答中似乎有一些信息 你检查它的存在是因为你想让你的程序读取它吗?要检查它们键的存在,可以将其包装在try except块中。这将防止“竞争条件”尝试读取密钥,在(不太可能的)事件中,在检查其存在和实际读取密钥之间对其进行修改。比如: from _winreg import * key_to_read = r'SOFTWARE\Microsoft\Windows\CurrentV

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


如何执行此操作,或者需要什么代码来检查注册表项是否存在?

前面的回答中似乎有一些信息

你检查它的存在是因为你想让你的程序读取它吗?要检查它们键的存在,可以将其包装在
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

这是一篇比较老的帖子,但我觉得在进行了一些类似的搜索之后,我想我会给它添加一些信息<据我所知,code>winreg,仅在Windows环境下工作。通过williballenthin可以用于跨平台操作,并且在使用注册表时有很多很好的选择

如果您有一个目标键,其中包含要提取的值,那么可以按照以下步骤将其列出……首先,导入模块(pip安装python注册表)。当主文件夹插入到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
它返回

Sorry Bud, no key values found at : ControlSet001\Control\TimeZoneInformation123

似乎有答案。@edwin-s此cheack注册表项存在或注册表存在??我将在答案中提供更多详细信息。不起作用,并且您忘记了reg=ConnectRegistry(无,HKEY_LOCAL_机器)必须是aReg=ConnectRegistry(无,HKEY_LOCAL_机器)
Sorry Bud, no key values found at : ControlSet001\Control\TimeZoneInformation123