如何存储环境变量

字母数字

要使用Windows命令处理器(cmd设置环境变量,请执行以下操作

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

MY_VARIABLE现在可以通过在同一cmd窗口启动的Python应用程序进行访问

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

我想知道是否有一种方法可以从Python内部设置环境变量,以使该变量可用于在同一计算机上运行的其他进程吗?设置新的环境变量:

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

但是NEW_VARIABLE,一旦Python处理并退出,它就会丢失。

斯蒂芬·劳赫(Stephen Rauch)

您可以将环境变量永久存储在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')

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章