I’m trying to implement a simple interface the create, set , get and delete registry key with winreg in Python.
Here is my code:
import winreg
REG_PATH = r"SOFTWAREMyApplication"
class RegistryMgr:
@staticmethod
def set_reg(name, value):
'''
Sets the specified key @ REG_PATH to the specified value.
If the key does not exist, it is created.
'''
with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, REG_PATH, 0, winreg.KEY_WRITE) as registry_key:
winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
@staticmethod
def get_reg(name):
'''
Reads and returns the specified key @ REG_PATH.
Returns None if the key does not exist.
'''
try:
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH, 0, winreg.KEY_READ) as registry_key:
value, _ = winreg.QueryValueEx(registry_key, name)
return value
except WindowsError:
return None
@staticmethod
def delete_reg(name):
'''
Deletes the specified key @ REG_PATH.
'''
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH, 0, winreg.KEY_ALL_ACCESS) as registry_key:
winreg.DeleteKey(registry_key, name)
When I test with the code below, I a get a “[WinError 2] The system cannot find the file specified” at line 3, which doesn’t make sense to me since the key exists.
RegistryMgr.set_reg("CONF_PATH", "C:some_location")
value = RegistryMgr.get_reg("CONF_PATH")
RegistryMgr.delete_reg("CONF_PATH")
value = RegistryMgr.get_reg("CONF_PATH")
RegistryMgr.set_reg("CONF_PATH", "C:some_other_location")
value = RegistryMgr.get_reg("CONF_PATH")
Can someone tell me what is the issue with my implementation for delete_reg
?