简体   繁体   中英

How to apply/save Python WINREG changes real-time

import winreg

REG_PATH = r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer"

def set_reg(name, value):
    try:
        winreg.CreateKey(winreg.HKEY_CURRENT_USER, REG_PATH)
        registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH, 0, 
                                       winreg.KEY_WRITE)
        winreg.SetValueEx(registry_key, name, 0, winreg.REG_DWORD, value)
        winreg.CloseKey(registry_key)
        return True
    except WindowsError:
        return False

def get_reg(name):
    try:
        registry_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, REG_PATH, 0,
                                       winreg.KEY_READ)
        value, regtype = winreg.QueryValueEx(registry_key, name)
        winreg.CloseKey(registry_key)
        return value
    except WindowsError:
        return None


#Read value 
print (get_reg('NoLogOff'))

#Set Value (will just write the value to reg, the changed val requires a win re-log to apply*)

set_reg('NoLogOff',1)

#will then apply the registry changes

The code above will change the NoLogOff value to 1, but will not save/apply in the actual windows registry. Is there anything I can do to have this done in real time?

The code will change the value in the Windows Registry. If you're using regedit you must make sure you refresh in order to view the changes.

Keep in mind many changes to the Windows Registry require a computer restart (or at least a logout from the current user) in order to reload the settings and actually apply them. This is unavoidable for most values.

If you wish to force the registry key changes on the disk and bypass the Windows lazy flush, you can use winreg.FlushKey(registry_key) before closing. However, It still does not guarantee the settings will apply immediately without restart, only that the registry will be saved to disk.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM