Python has a module to access the Windows registry. It comes together in the standard library, no need to import anything external.
import winreg
This module has a function that takes an HKEY and an index, and returns the HKEY key name on that index. If the index is invalid, it releases a Windowserror. Thus it is possible to get the name of all the immediate subchaves of a given HKEY.
def obter_subchaves_imediatas(hkey):
i = 0
try:
while True:
yield winreg.EnumKey(hkey, i)
i += 1
except WindowsError:
pass
Now, using the above function, it is easy to write a routine that recursively navigates through the entire record tree. It’s basically the pre-order browsing algorithm in some tree.
def navegar_arvore(nome_chave_raiz):
hkey = winreg.OpenKey(winreg.HKEY_CURRENT_USER, nome_chave_raiz)
for nome_subchave in obter_subchaves_imediatas(hkey):
nome_completo = f'{nome_chave_raiz}\\{nome_subchave}'
yield nome_completo
yield from navegar_arvore(nome_completo)
A simple loop lets you get all paths from a certain root.
for chave in navegar_arvore('Control Panel'):
print(chave)
There are several points that can be improved in this code, but what was shown here is enough to solve the problem.
If you just want to make sure that a key exists, why go through the whole record? in any case, you can use the function
EnumKey
moduleWinreg
to enumerate the keys.– stderr
I want to kind of do a search through the registry without having a predefined path. For example: find the key x across the registry.
– Lollorcaust
Got it, do you want to find only the first occurrence or keep looking? maybe recursion is necessary in this case.
– stderr
The key would happen to be the PATH?
– Vinicius Mesel