How to Set Environment Variable using Python?
In the previous article, we have seen how to set the environment variables with GUI, PowerShell, and CMD. In this section, let’s continue to set the environment variable programmatically using Python
Set Environment Variable using Python
a. Process Level
Setting up environment variables at the process level is easy with Python. We need to import the OS module and use the environment function to set the value.
For Example,
import os
os.environ["azSub"] = "TestSub1"
print(os.environ["azSub"])
Setting up environment variables at the machine or user levels isn’t straightforward in Python like PowerShell. We need to set the registry keys for them. Let’s have a look.
b. Machine-Level
To set environment variables at the machine level with Python, the registry value should be set. The path for the registry value is, SYSTEM\CurrentControlSet\Control\Session Manager\Environment.
import os
import winreg
def set_machine_env_variable(variable_name, variable_value):
key_path = r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
try:
# Open the registry key for environment variables with write access
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path, 0, winreg.KEY_SET_VALUE)
# Set the environment variable in the registry
winreg.SetValueEx(key, variable_name, 0, winreg.REG_EXPAND_SZ, variable_value)
# Close the registry key
winreg.CloseKey(key)
print(f"Machine-level environment variable {variable_name} set to {variable_value}.")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
variable_name = 'azSub'
variable_value = 'TestSub4'
set_machine_env_variable(variable_name, variable_value)
c. User-Level
Similarly, for the user level, you just need to change the registry key path as shown below.
import os
import winreg
def set_user_env_variable(variable_name, variable_value):
key_path = r"Environment"
try:
# Open the registry key for environment variables with write access
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path, 0, winreg.KEY_SET_VALUE)
# Set the environment variable in the registry
winreg.SetValueEx(key, variable_name, 0, winreg.REG_EXPAND_SZ, variable_value)
# Close the registry key
winreg.CloseKey(key)
print(f"User-level environment variable {variable_name} set to {variable_value}.")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
variable_name = 'azsub'
variable_value = 'TestSub4'
set_user_env_variable(variable_name, variable_value)
You can get the code at the GitHub repo below.
https://github.com/chiragce17/MyPublicRepo/tree/main/Python/Windows/EnvironmentVariable
Pingback: How to Set Environment Variable in Windows using GoLang? > The Automation Code
Pingback: How to set environment variables using PowerShell? > The Automation Code