To set an environment variable using Windows Command Processor ( cmd
) :
SET MY_VARIABLE=c:\path\to\filename.txt
MY_VARIABLE
now can be accessed by Python application started by same cmd
window:
import os
variable = os.getenv('MY_VARIABLE')
I wonder if there is a way to set an environment variable from inside of Python so it becomes available to other processes running on the same machine? To set a new environment variable:
os.environ['NEW_VARIABLE'] = 'NEW VALUE'
But this NEW_VARIABLE
is lost as soon Python process and exited.
You can store environment variables persistently in the Windows registry. Variables can be stored for the current user, or for the system:
Code to persistently set an environment variable on 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)
Test code to invoke above:
set_environment_variable('NEW_VARIABLE', 'NEW VALUE')