0

I am writing a python program that needs to store a value in a persistent user environment variable. I believe these values are stored in the registry. I have tried something like this using the winreg python module.

key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Environment', access=winreg.KEY_WRITE) winreg.SetValueEx(key, envVarName, 0, winreg.REG_SZ, envVarValue) winreg.Close(key)

I can see from using Registry Editor that this value is successfully set. But if I try and read the value from another python script or from a new powershell instance, I don't see the new value until the machine is rebooted.

What else do I need to do to make this value available to other processes without rebooting?

cmking
  • 41
  • 2

2 Answers2

1

Looking at this answer gives a possible answer: https://stackoverflow.com/a/61757725/18300067

os.system("SETX {0} {1} /M".format("start", "test"))
Ricky Chau
  • 49
  • 3
  • Using setx in a subprocess is how we have been doing it but it is super slow. Like a second or so to set a value. I was really hoping for a better way. – cmking Feb 24 '22 at 16:38
0

This is how we do it in production on one of Windows servers (code is simplified):

import winreg

regdir = "Environment-test"
keyname = "Name-test"
keyvalue = "Value-test"

def setRegistry(regdir, keyname, keyvalue):
    with winreg.CreateKey(winreg.HKEY_CURRENT_USER, regdir) as _:
        with winreg.OpenKey(winreg.HKEY_CURRENT_USER, regdir, 0, winreg.KEY_WRITE) as writeRegistryDir:
            winreg.SetValueEx(writeRegistryDir, keyname, 0, winreg.REG_SZ, keyvalue)

def getRegistry(regdir, keyname):
    with winreg.OpenKey(winreg.HKEY_CURRENT_USER, regdir) as accessRegistryDir:
        value, _ = winreg.QueryValueEx(accessRegistryDir, keyname)
        return(value)

If I firstly set the value using:

setRegistry(regdir, keyname, keyvalue)

Then check if it's created:

enter image description here

Now I use the getRegistry and open a PS in admin mode to run it:

print(getRegistry(regdir, keyname))

enter image description here

Cow
  • 2,543
  • 4
  • 13
  • 25
  • This sets the value in the registry. The part that I am not getting is how to get values that are set in the Environment registry to be read by new processes with out doing a reboot. – cmking Feb 24 '22 at 16:40
  • @cmking I did not have to reboot. Worked fine the first time. – Cow Feb 24 '22 at 17:29
  • Did it work to read them as environment variables? By using $env:keyName in a new powershell window for example. This definitely did not work for me. – cmking Feb 24 '22 at 18:18