繁体   English   中英

如何存储环境变量

[英]How to store environment variables

使用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进程并退出。

您可以在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')

一个简单的,如果不是稍微粗略的方式这样做只是使用os.system并传递命令,就像你在CMD中运行它一样?

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

希望有所帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM