Verificando se a chave de registro existe com python
-
21-12-2019 - |
Pergunta
Estou procurando uma maneira de verificar se existe uma chave de registro com python.
Como posso fazer isso ou qual código preciso para verificar se existe ou não uma chave de registro?
Solução
Parece haver alguma informação em uma resposta anterior aqui.
Você está verificando sua existência porque deseja que seu programa o leia?Para verificar a existência da chave, você pode envolvê-la em um try-except
bloquear.Isso evitará que "condições de corrida" tentem ler a chave, no caso (improvável) de ela ser modificada entre a verificação de sua existência e a leitura real da chave.Algo como:
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
Outras dicas
Este é um post mais antigo, mas depois de algumas pesquisas semelhantes, pensei em adicionar algumas informações a ele. winreg
, pelo que descobri, só funciona em um ambiente Windows. registro python por williballenthin pode ser usado para fazer isso em plataforma cruzada e tem uma infinidade de ótimas opções ao trabalhar com o Registro.
Se você tiver uma chave de destino com valores que deseja extrair, poderá listá-los seguindo estas etapas... Primeiro, importe os módulos (pip install python-registry).Isso pode não funcionar porque a pasta master é inserida em libs/sitepackages, certifique-se de que o Registro pasta está na raiz dos pacotes do site.
from Registry import Registry # Ensure Registry is in your libs/site-packages
Em seguida, crie sua função e certifique-se de adicionar um try:
e except
em sua função para verificar se está lá.
# 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
Você pode criar um ditado de tudo o que deseja verificar e apenas iterá-lo com esse processo para verificar vários de uma vez ou apenas um de cada vez.Aqui está um exemplo prático:
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()
Que retorna,
Sorry Bud, no key values found at : ControlSet001\Control\TimeZoneInformation123