Verifica se la chiave del registro esiste con Python
-
21-12-2019 - |
Domanda
Sto cercando un modo per verificare se esiste una chiave di registro con Python.
Come posso fare questo o quale codice devo controllare se esiste una chiave di registro o no?
Soluzione
Sembra che ci siano alcune informazioni in una risposta precedente qui .
Stai controllando la sua esistenza perché vuoi che il tuo programma legga?Per verificare l'esistenza della chiave, è possibile avvolgerlo in un blocco try-except
.Ciò impedirà a "Condizioni di gara" che tenta di leggere la chiave, nell'evento (improbabile) che viene modificato tra il controllo della sua esistenza e realmente leggendo la chiave.Qualcosa come:
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
. Altri suggerimenti
Questo è un post più vecchio, ma ho sentito dopo alcune ricerche simili, pensai aggiungere alcune informazioni a questo. winreg
, da quello che ho trovato, funziona solo su un ambiente Windows. Python-Registry di Willibalthin può essere utilizzato per fare questo cross- piattaforma e ha una moltitudine di grandi opzioni quando si lavora con il registro.
Se si dispone di un tasto di destinazione che ha valori che si desidera estrarre, è possibile elencarli seguendo questi passaggi .... Innanzitutto, i moduli di importazione (PIP Installa Python-Registry). Questo potrebbe non funzionare come la cartella principale viene inserita nei libs / sitipackages, assicurarsi che la cartella Registry sia nella radice dei pacchetti del sito.
from Registry import Registry # Ensure Registry is in your libs/site-packages
.
Avanti Crea la tua funzione e assicurati di aggiungere in un try:
e except
into la tua funzione per verificare se è 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
.
Puoi fare un traffico di tutto ciò che vuoi controllare e semplicemente iterali attraverso questo con questo processo per controllare diversi contemporaneamente o solo uno alla volta. Ecco un esempio di funzionamento:
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()
.
che restituisce,
Sorry Bud, no key values found at : ControlSet001\Control\TimeZoneInformation123
.