Print Environment Variables in Python

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.

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:

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,

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,

Output:

KeyError: 'LOG_NAME11'

To avoid that, use <dict>.get(<key>). This method returns None if the key is not available. For example,

Output:
None

You can also use the os.getenv(<key>) function.

Output:

/home/kiprono/Desktop/Print Environment Variables in Python
None