Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting windows system PATH in Registry via Python winreg

I've written a program to add directories to the PATH variable via the registry, either the HKCU(user) or HKLM(system) path, depending on an input option.

It works fine when using the User path. However, when setting the path for the System, Windows acts as if the path variable is empty, e.g.

'notepad' is not recognized as an internal or external command....

However, echo %path% prints everything out appropriately, without any syntax errors. Similarly, if I view the variable in the System Properties GUI, it shows my full path appropriately, e.g.

%SystemRoot%\system32;%SystemRoot%;

Now, if I manually open that variable in the GUI, and add OR remove the trailing semicolon (i.e. make a noticeable but seemingly irrelevant change), then the path seems to work fine.

Yes, I am opening a new command window to check the path. Restarting the machine doesn't seem to do anything either.

Any ideas?

Code excerpt is here:

import _winreg as registry

#HKEY_LOCAL_MACHINE\
SYS_ENV_SUBPATH = r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

#HKEY_CURRENT_USER\
USR_ENV_SUBPATH = r"Environment"

def update_reg_path_value(paths_to_add,privilege):
    env_key = open_env_registry_key(privilege)
    current_path = get_path_from_registry_or_create(env_key)
    val_string = create_new_path_value(current_path, paths_to_add)
    registry.SetValueEx(env_key,"Path",0,registry.REG_SZ,val_string)


def open_env_registry_key(privilege):
    if privilege == 'system':
        return registry.OpenKey(registry.HKEY_LOCAL_MACHINE,SYS_ENV_SUBPATH,
                            0,registry.KEY_ALL_ACCESS)
    return registry.OpenKey(registry.HKEY_CURRENT_USER,USR_ENV_SUBPATH,
                        0,registry.KEY_ALL_ACCESS)
like image 439
tenwest Avatar asked Jul 10 '26 03:07

tenwest


1 Answers

As in the comments, changing REG_SZ to REG_EXPAND_SZ did the trick, as variables using "%" weren't being recognized. This also works when no "%"s exist, so I use it for the user path as well rather than needing to switch between the two.

registry.SetValueEx(env_key,"Path",0,registry.REG_EXPAND_SZ,val_string)

like image 150
tenwest Avatar answered Jul 14 '26 19:07

tenwest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!