[英]Python Windows Registry: Display List of Profiles
我是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
当我尝试运行上述内容时,我得到以下内容:
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-45-6261438d1fdc> in <module>()
----> 1 l = get_profiles()
<ipython-input-44-f572c6ac8843> in get_profiles()
4 regKey = OpenKey(HKEY_LOCAL_MACHINE,
5 r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList')
----> 6 recent = QueryValueEx(regKey,'DisplayName')[0]
7 recent_list = []
8 for subkey in recent:
FileNotFoundError: [WinError 2] The system cannot find the file specified
我有预感'DisplayName'
部分是错误的,我应该如何纠正它?
您可以使用EnumKey
获取打开的注册表项的子键。
winreg.EnumKey (键,索引)
枚举打开的注册表项的子项,返回一个字符串。
key是一个已经打开的键,或者是一个预定义的HKEY_ *常量。
index是一个整数,用于标识要检索的键的索引。
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
对象实现__exit__()
__enter__()
和__exit__()
,因此支持with语句的上下文协议:
with OpenKey(HKEY_LOCAL_MACHINE, "foo") as key:
... # work with key
当控件离开with块时,将自动关闭键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.