Environment variables are computer values that affect various aspects of a program and the entire computer system.
Print All Environment Variables
All environment variables (both system and user variables) can be assessed using the os.environ attribute.
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 the native Python dictionary.
1 2 3 |
import os print(os.environ) |
Output on my Debian Linux (truncated):
environ({'USER': 'kiprono', 'LC_TIME': 'en_US.UTF-8', 'XDG_SESSION_TYPE': 'wayland', 'SHLVL': '1', 'HOME': '/home/kiprono', …, 'PYTHONIOENCODING': 'utf-8'})
Output on my Windows (truncated):
environ({'ALLUSERSPROFILE': 'C:\\ProgramData', 'APPDATA': 'C:\\Users\\kipro\\AppData\\Roaming', 'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files', …, 'PYTHONIOENCODING': 'utf-8'})
You can also loop through the os.environ items and print the key-value pays as follows:
1 2 3 4 |
import os for key, value in os.environ.items(): print(key,"--->",value) |
Output on my Debian Linux (truncated):
USER ---> kiprono LC_TIME ---> en_US.UTF-8 XDG_SESSION_TYPE ---> wayland SHLVL ---> 1 HOME ---> /home/kiprono DESKTOP_SESSION ---> gnome … SSL_CERT_FILE ---> /opt/sublime_text/Lib/python3/certifi/cacert.pem PYTHONIOENCODING ---> utf-8
Access a Given Environment Variables
As said earlier, os.environ output supports all operations of a Python dictionary. For example,
1 2 3 4 5 6 7 8 9 |
# Accessing Environment Variables using the keys path_variable = os.environ["PATH"] print(path_variable) home_variable = os.environ["HOME"] print(home_variable) home_variable = os.environ["LOGNAME"] print(home_variable) |
Output:
/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/snap/bin /home/kiprono kiprono
If a key (environment variable) is not present, attempting to access it using the above method will raise a KeyError. For example,
1 2 3 |
var1 = os.environ["LOG_NAME11"] print(var1) |
Output:
KeyError: 'LOG_NAME11'
To avoid that, use <dict>.get(<key>). This method returns None if the key is not available. For example,
1 2 3 |
var1 = os.environ.get("LOG_NAME11") print(var1) |
Output:
None
You can also use the os.getenv(<key>) function.
1 2 3 4 5 6 7 8 |
# Available variable. # PWD is the Present Working Directory var1 = os.getenv("PWD") print(var1) # Variable that doesn't exist. Returns None var2 = os.getenv("PWD12") print(var2) |
Output:
/home/kiprono/Desktop/Print Environment Variables in Python None