Saturday, February 27, 2016

Python’s winreg: Editing the Windows Registry

# Author: Donghua# Purpose: Demonstration
import sys
import winreg
import traceback


RegPath='SOFTWARE\Python\DemoKey'NewKey='Key1'NewValueName='Val1'NewStringValue='DemoValue'
def QueryKeyValue():

    # Query the default value for KEY1    try:
        with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, RegPath) as key:
            ExistValue=winreg.QueryValue(key,NewKey)
            print('New Key (Default) value:',ExistValue)
    except FileNotFoundError:
         print(traceback.format_exc())

      # Set the string value (Val1) under KEY1    try:
        with winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, RegPath,0,access=winreg.KEY_READ) as key:
            ExistValue=winreg.QueryValueEx(key,NewValueName)
            print('New String value:',ExistValue[0])
    except FileNotFoundError:
         print(traceback.format_exc())

    return
def SetKeyValue():
    # set the default value for KEY1    try:
        with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, RegPath) as key:
            winreg.SetValue(key,NewKey,winreg.REG_SZ,'Default Key Value Demo')
    except FileNotFoundError:
        try:
            key=winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, RegPath)
            winreg.SetValue(key,NewKey,winreg.REG_SZ,'Default Value Demo')
        except:
            print(traceback.format_exc())
    except:
        print(traceback.format_exc())

    # Set the string key/value pair under KEY1    try:
        with winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, RegPath,reserved=0,access=winreg.KEY_WRITE) as key:
            winreg.SetValueEx(key,NewValueName,0,winreg.REG_SZ, NewStringValue)
    except:
        try:
            key=winreg.CreateKeyEx(winreg.HKEY_LOCAL_MACHINE, RegPath,reserved=0,access=winreg.KEY_WRITE)
            winreg.SetValueEx(key,NewValueName,0,winreg.REG_SZ, NewStringValue)
        except:
            print(traceback.format_exc())
    return
def DelKeyValue():
    try:
        with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, RegPath, reserved=0,access=winreg.KEY_WRITE) as key:
            # Delete Value Val1 under Key1            try:
                winreg.DeleteValue(key,NewValueName)
                print('Value deleted:', NewValueName)
            except:
                print(traceback.format_exc())
            # Delete Key Key1            try:
                winreg.DeleteKey(key,NewKey)
                print('Key deleted:', NewKey)
            except:
                print(traceback.format_exc())
    except FileNotFoundError:
        print(traceback.format_exc())
    return
if __name__ == "__main__":
    SetKeyValue()
    QueryKeyValue()
    DelKeyValue()