如何存储环境变量

How to store environment variables

使用 Windows 命令处理器(cmd)设置环境变量:

SET MY_VARIABLE=c:\path\to\filename.txt

MY_VARIABLE 现在可以被同一个 cmd 启动的 Python 应用程序访问 window:

import os
variable = os.getenv('MY_VARIABLE') 

我想知道是否有办法从 Python 内部设置一个环境变量,以便同一台机器上的其他进程 运行 可以使用它? 设置新的环境变量:

os.environ['NEW_VARIABLE'] = 'NEW VALUE'

但是这个 NEW_VARIABLE 会在 Python 处理并退出后立即丢失。

如果不是简单粗暴的方法,是否可以简单地使用 os.system 并通过它传递命令,就好像您是 运行 在 CMD 中一样?

一个例子是os.system("SET MY_VARIABLE=c:\path\to\filename.txt")

希望对您有所帮助。`

您可以在 Windows 注册表中永久存储环境变量。可以为当前用户或系统存储变量:

在 Windows 上永久设置环境变量的代码:

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

def set_environment_variable(variable, value, user_env=True):
    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)

    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)

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

上面调用的测试代码:

set_environment_variable('NEW_VARIABLE', 'NEW VALUE')