All environment variables (both system and user variables) can be assessed on the os.environ attribute in Python.
The attribute returns a dictionary of all environment variables with keys as the variable names and values as environment values. The resulting dictionary supports all the operations of a native Python dictionary.
This article focuses on setting environment variables – temporarily for the current Python session and permanently for persistent variable change.
Printing Environment Variables
1 2 3 |
import os print(os.environ) |
Output (truncated):
environ({'KDE_FULL_SESSION': 'true', 'USER': 'kiprono', 'LC_TIME': 'en_US.UTF-8', 'XDG_SEAT': 'seat0', 'SSH_AGENT_PID': '1704', 'XDG_SESSION_TYPE': 'x11', 'XCURSOR_SIZE': '24', 'SHLVL': '1', 'HOME': '/home/kiprono',...)
Accessing a Variable
You can use os.getenv(<var>) or os.environ.get(<var>) to get the value of <var>. For example,
1 2 3 4 5 6 7 8 9 |
import os home = os.getenv("HOME") print(home) # os.getenv() returns None if the variable does not exist. home23 = os.getenv("HOME23") print(home23) path = os.environ.get("PATH") print(path) |
Output:
/home/kiprono None /home/kiprono/.local/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/snap/bin
Setting Environment Variable
Just like you would do a native Python dictionary, you can set environment variable using the syntax os.environ[<variable>] = new_environment_value.
The following example sets the $HOME variable into a new path.
1 2 3 4 5 6 7 8 |
import os # Checking the environment value of $HOME before changing print(os.environ["HOME"]) # Setting the $HOME directory to a new path (Desktop) os.environ["HOME"] = "/home/kiprono/Desktop" # Printing the environment value after changing. print(os.environ["HOME"]) |
Output:
/home/kiprono /home/kiprono/Desktop
As shown in the output, the $HOME directory has been updated. Note that if the environment variable did not exist already, the method above would create it.
Important Note
The change made on the environment variable(s) using the method above will only exist for the current session of the Python interpreter.
If you want the changes on the environment to persist after ending the Python session, you must edit the user profile.
We can do that with the following code syntax.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import subprocess import os if os.name == "posix": # For Linux and Mac bashrc_file = os.path.expanduser("~/.bashrc") # Open bashrc_file in append ("a") mode with open(bashrc_file, "a") as f: f.write("export <var>='value'") if os.name == "nt": # For Windows print("This is Windows") command = "setx <var> 'value'" subprocess.Popen(command, shell=True).wait() |
Note (for Windows): The code above changes the variables <var> for the current user. If you want the variables to be available for global usage, use “setx /M <var> ‘value’” (it may need elevation of privileges).
Note (for Mac OS): The profile might be located in the .profile or .bash_profile file on the home directory instead of the .bashrc.
Conclusion
This article discussed two ways of setting environment variables using Python. The first changes the environment for the current Python session, and the last section discusses how to make permanent changes to the environment variables.