Python Practice › OS Module Programs › Program 4
List environment variables
Write a Python program to get the list of environment variables with os.environ.
Output
True True
Approach
os.environbehaves like a dictionary.
Solution
import os names = sorted(os.environ)print(len(names) > 0)print("PATH" in names)for name in names[:0]: print(name, "=", os.environ[name])Output
True True
Line by line
Line 3
sorted() of the mapping gives the variable names.
Watch out
The loop is limited to [:0] here on purpose: environment values often contain paths, user names and secrets, so print them only on your own machine.
Learn the concept
New to this topic? Read the lesson, then come back.