通过 Python winreg 在注册表中设置 Windows 系统路径 [英] Setting windows system PATH in Registry via Python winreg

查看:92
本文介绍了通过 Python winreg 在注册表中设置 Windows 系统路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个程序,通过注册表将目录添加到 PATH 变量中,可以是 HKCU(用户)或 HKLM(系统)路径,具体取决于输入选项.

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.

使用用户路径时效果很好.但是,在为系统设置路径时,Windows 的行为就像路径变量为空一样,例如

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' 未被识别为内部或外部命令....

然而,echo %path% 会适当地打印出所有内容,没有任何语法错误.同样,如果我在系统属性 GUI 中查看变量,它会适当地显示我的完整路径,例如

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%;

现在,如果我在 GUI 中手动打开该变量,并添加或删除结尾的分号(即进行明显但看似无关的更改),那么路径似乎工作正常.

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.

有什么想法吗?

代码摘录在这里:

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)

推荐答案

在评论中,将 REG_SZ 更改为 REG_EXPAND_SZ 可以解决问题,因为变量使用了%"没有被认可.这也适用于不存在%"的情况,因此我也将其用于用户路径,而无需在两者之间切换.

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)

这篇关于通过 Python winreg 在注册表中设置 Windows 系统路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆