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?

0

2 Answers 2

1

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

os.system("SETX {0} {1} /M".format("start", "test"))
Sign up to request clarification or add additional context in comments.

1 Comment

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.
1

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

3 Comments

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 I did not have to reboot. Worked fine the first time.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.