Skip to content
Home / Fundamentals

How to Access Environment Variables in Python

Environment variables are key-value pairs that can be used to store and retrieve information such as system paths, database credentials, and other configuration data. In Python, you can access environment variables using the os module.

Here are some examples of how to access environment variables in Python:

Accessing a Single Environment Variable

To access a single environment variable, you can use the os.environ object, which is a dictionary-like object that allows you to access the environment variables as keys. For example, to access the PATH environment variable, you can do the following:

import os

path = os.environ['PATH']
print(path)

This will print the value of the PATH environment variable to the console.

Accessing Multiple Environment Variables

To access multiple environment variables, you can use the os.environ.get() method, which allows you to specify a default value to be returned if the requested environment variable does not exist. For example:

import os

database_url = os.environ.get('DATABASE_URL', 'postgres://localhost')
api_key = os.environ.get('API_KEY', 'my-api-key')

print(database_url)
print(api_key)

This will print the values of the DATABASE_URL and API_KEY environment variables to the console. If either of these variables is not set, the default value specified in the get() method will be used instead.

Accessing All Environment Variables

To access all environment variables, you can use the os.environ object as an iterable. For example:

import os

for key, value in os.environ.items():
    print(f'{key}: {value}')

This will print all of the environment variables and their values to the console.

Setting Environment Variables To set an environment variable in Python, you can use the os.environ object as if it were a dictionary. For example:

import os

os.environ['MY_VAR'] = 'my-value'

This will set the MY_VAR environment variable to the value 'my-value'. Keep in mind that changes made to the environment variables using the os.environ object are only temporary and will not persist after the Python script has finished executing.