Pregunta

Estoy buscando una manera de comprobar si existe una clave de registro con Python.

¿Cómo puedo hacer esto o qué código necesito para verificar si existe una clave de registro o no?

¿Fue útil?

Solución

Parece haber alguna información en una respuesta anterior. aquí.

¿Estás comprobando su existencia porque quieres que tu programa lo lea?Para verificar la existencia de su clave, puede envolverla en un try-except bloquear.Esto evitará que las "condiciones de carrera" intenten leer la clave, en el (improbable) caso de que se modifique entre verificar su existencia y leer la clave.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

Otros consejos

Esta es una publicación anterior, pero después de una búsqueda similar sentí que agregaría algo de información. winreg , por lo que he encontrado, sólo funciona en un entorno Windows. registro-python por williballenthin se puede utilizar para hacer esto multiplataforma y tiene una multitud de excelentes opciones cuando se trabaja con el Registro.

Si tiene una clave de destino que tiene valores que desea extraer, puede enumerarlos siguiendo estos pasos... Primero, importe los módulos (pip install python-registry).Es posible que esto no funcione ya que la carpeta maestra se inserta en libs/sitepackages, asegúrese de que Registro La carpeta está en la raíz de los paquetes del sitio.

from Registry import Registry         # Ensure Registry is in your libs/site-packages

Luego cree su función y asegúrese de agregar un try: y excepten su función para comprobar si está allí.

# 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

Puede hacer un dictado de todo lo que desea verificar y simplemente repetirlo con este proceso para verificar varios a la vez, o solo uno a la vez.Aquí hay un ejemplo práctico:

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 regresa,

Sorry Bud, no key values found at : ControlSet001\Control\TimeZoneInformation123
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top