如何从注册表中删除Windows用户环境变量

2024-09-27 09:32:05 发布

您现在位置:Python中文网/ 问答频道 /正文

通过这个简单的设置,我可以在注册表中创建任何用户环境变量:

import win32con
import win32gui
import _winreg as winreg

def set_environment_variable(variable, value, user_env=True):
    if user_env: reg_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Environment', 0, winreg.KEY_SET_VALUE)
    else: reg_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment', 0, winreg.KEY_SET_VALUE)

    if '%' in value: var_type = winreg.REG_EXPAND_SZ
    else: var_type = winreg.REG_SZ

    with reg_key:
        winreg.SetValueEx(reg_key, variable, 0, var_type, value)     
    win32gui.SendMessageTimeout(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment', win32con.SMTO_ABORTIFHUNG, 1000)

创建MY_VARIABLE

^{pr2}$

以下是截图:

enter image description here

问题:如何删除刚刚创建的MY_VARIABLE?在


Tags: keyimportenvifenvironmentvaluevartype
1条回答
网友
1楼 · 发布于 2024-09-27 09:32:05

您可以使用以下方法轻松地从Windows注册表中设置或删除环境变量:

def set_environment_variable(variable, value, user_env=True):
    """
    Set/Remove Environment variable from windows registry.

    :param variable: Environment Variable Name
    :param value: Environment Variable Value (None to delete)
    :param user_env: if true set in user env instead of in system env
    :return: None
    """
    if user_env:
        # This is for the user's environment variables
        reg_key = winreg.OpenKey(
            winreg.HKEY_CURRENT_USER,
            'Environment', 0, winreg.KEY_SET_VALUE)
    else:
        # This is for the system environment variables
        reg_key = winreg.OpenKey(
            winreg.HKEY_LOCAL_MACHINE,
            r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment',
            0, winreg.KEY_SET_VALUE)

    with reg_key:
        if value is None:
            winreg.DeleteValue(reg_key, variable)
        else:
            if '%' in value:
                var_type = winreg.REG_EXPAND_SZ
            else:
                var_type = winreg.REG_SZ
            winreg.SetValueEx(reg_key, variable, 0, var_type, value)

    # notify about environment change
    win32gui.SendMessageTimeout(
        win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0,
        'Environment', win32con.SMTO_ABORTIFHUNG, 1000)

要设置环境变量:

^{pr2}$

要删除环境变量:

set_environment_variable('MY_VARIABLE', None)

您可以通过以下方式导入win32库:

import win32con
import win32gui
try:
    import _winreg as winreg
except ImportError:
    # this has been renamed in python 3
    import winreg

相关问题 更多 >

    热门问题