Trusted answers to developer questions

How to list all the environment variables in Python

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

Using os.environ

The os.environ is an object that represents users’ environment variables and their values. It gives you a dictionary with the user’s environmental variable names as they keys and their values as the values. The dictionary supports all the operations of the dictionary data structure in Python.

Listing all the environment variables

In the code below, we loop through the dictionary returned by the os.environ. The key is the name, and value is the value of the environment variables:

import os
for name, value in os.environ.items():
print("{0}: {1}".format(name, value))

How to get the value of a specific environment variable

We use the get() method on the dictionary returned by os.environ to get the value of a specific environment variable.

import os
name = "PATH"
print(os.environ.get(name))

RELATED TAGS

python
Did you find this helpful?