pythonwindows注册表:显示配置文件列表

2024-09-28 22:23:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我不熟悉Windows注册表,目前正在尝试使用Python从Windows注册表中获取一个配置文件名的列表,但我不确定我做错了什么。我的代码如下:

from winreg import *
def get_profiles():

    regKey = OpenKey(HKEY_LOCAL_MACHINE,
        r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList')
    recent = QueryValueEx(regKey,'DisplayName')[0]
    recent_list = []
    for subkey in recent:
        recent_list.append(QueryValueEx(regKey,subkey)[0])
    return recent_list

当我试着在上面跑的时候:

^{pr2}$

我预感到'DisplayName'部分是错误的,我应该如何更正它?在


Tags: 代码fromimport列表文件名注册表windowsdef
1条回答
网友
1楼 · 发布于 2024-09-28 22:23:53

您可以使用EnumKey获取打开的注册表项的子项。在

winreg.EnumKey(key, index)

Enumerates subkeys of an open registry key, returning a string.

key is an already open key, or one of the predefined HKEY_* constants.

index is an integer that identifies the index of the key to retrieve.

from contextlib import suppress
from winreg import \
    (OpenKey,
     HKEY_LOCAL_MACHINE,
     QueryInfoKey,
     QueryValueEx,
     EnumKey)


PROFILE_REGISTRY = "SOFTWARE\\Microsoft\\WindowsNT\\CurrentVersion\\ProfileList"


def get_profile_attribute(*, attribute):
    profile_to_sub_key_map = {}
    with OpenKey(HKEY_LOCAL_MACHINE, PROFILE_REGISTRY) as key:
        number_of_sub_keys, _, _ = QueryInfoKey(key)  # The `QueryInfoKey` Returns information about a key, as a tuple.
        # At the index 0  will be An integer giving the number of sub keys 
        # this key has.

        for index in range(number_of_sub_keys):
            sub_key_name = EnumKey(key, index)
            # Open the sub keys one by one and fetch the attribute.
            with OpenKey(HKEY_LOCAL_MACHINE,
                         f"{PROFILE_REGISTRY}\\{sub_key_name}") as sub_key:
                with suppress(FileNotFoundError):
                    registry_value, _ = QueryValueEx(sub_key, attribute)
                    profile_to_sub_key_map.update({sub_key_name: registry_value})

    return profile_to_sub_key_map


print(get_profile_attribute(attribute='ProfileImagePath'))

同时,根据文件说明。在

HKEY对象实现了__enter__()和{},因此支持with语句的上下文协议:

^{2}$

当控件离开with块时将自动关闭键。在

相关问题 更多 >