[python] How to access environment variable values?

I set an environment variable that I want to access in my Python application. How do I get its value?

This question is related to python environment-variables

The answer is


import os
for a in os.environ:
    print('Var: ', a, 'Value: ', os.getenv(a))
print("all done")

That will print all of the environment variables along with their values.


.env File

Here is my .env file (I changed multiple characters in each key to prevent people hacking my accounts).

SECRET_KEY=6g18169690e33af0cb10f3eb6b3cb36cb448b7d31f751cde
AWS_SECRET_ACCESS_KEY=18df6c6e95ab3832c5d09486779dcb1466ebbb12b141a0c4
DATABASE_URL='postgres://drjpczkqhnuvkc:f0ba6afd133c53913a4df103187b2a34c14234e7ae4b644952534c4dba74352d@ec2-54-146-4-66.compute-1.amazonaws.com:5432/ddnl5mnb76cne4'
AWS_ACCESS_KEY_ID=AKIBUGFPPLQFTFVDVIFE
DISABLE_COLLECTSTATIC=1
EMAIL_HOST_PASSWORD=COMING SOON
MAILCHIMP_API_KEY=a9782cc1adcd8160907ab76064411efe-us17
MAILCHIMP_EMAIL_LIST_ID=5a6a2c63b7
STRIPE_PUB_KEY=pk_test_51HEF86ARPAz7urwyGw9xwLkgbgfCYT48LttlwjEkb88I7Ljb5soBtuKXBaPiKfuu0Cx2BzIowR3jJFkC8ybFBAEf00DFY46tB8
STRIPE_SECRET_KEY=sk_test_19HEF55BCEAz7urwytx7tO3QCxV4R8DEFXbqj6esg7OKuybiSTI8iJD8mmJUQpg4RKENxuS04DKOCzYHpDkAjUttO00LOmsT5Eg

settings

I was told my data was corrupted. I was struggling to work out what was going on. I had a suspicion the values from .env were not being passed into my settings file.

print(os.environ.get('AWS_SECRET_ACCESS_KEY'))
print(os.environ.get('AWS_ACCESS_KEY_ID'))
print(os.environ.get('AWS_SECRET_ACCESS_KEY'))
print(os.environ.get('DATABASE_URL'))
print(os.environ.get('SECRET_KEY'))
print(os.environ.get('DISABLE_COLLECTSTATIC'))
print(os.environ.get('EMAIL_HOST_PASSWORD'))
print(os.environ.get('MAILCHIMP_API_KEY'))
print(os.environ.get('MAILCHIMP_EMAIL_LIST_ID'))
print(os.environ.get('STRIPE_PUB_KEY'))
print(os.environ.get('STRIPE_SECRET_KEY'))

The only value being printed correctly was the SECRET_KEY. I reviewed the .env file and for the life of me could not see any reason why the SECRET_KEY was working and nothing else.

I got everything working eventually by putting this above the print statements.

from dotenv import load_dotenv   #for python-dotenv method
load_dotenv()                    #for python-dotenv method

And doing

pip install -U python-dotenv

I am still not sure why SECRET_KEY was working when all the others were broken.


You can access to the environment variables using

import os
print os.environ

Try to see the content of PYTHONPATH or PYTHONHOME environment variables, maybe this will be helpful for your second question. However you should clarify it.


A performance-driven approach - calling environ is expensive, so it's better to call it once and save it to a dictionary. Full example:

from os import environ


# Slower
print(environ["USER"], environ["NAME"])

# Faster
env_dict = dict(environ)
print(env_dict["USER"], env_dict["NAME"])

P.S- if you worry about exposing private environment variables, then sanitize env_dict after the assignment.


You can also try this

First, install python-decouple

pip install python-decouple

import it in your file

from decouple import config

Then get the env variable

SECRET_KEY=config('SECRET_KEY')

Read more about the python library here


There's also a number of great libraries. Envs for example will allow you to parse objects out of your environment variables, which is rad. For example:

from envs import env
env('SECRET_KEY') # 'your_secret_key_here'
env('SERVER_NAMES',var_type='list') #['your', 'list', 'here']

If you are planning to use the code in a production web application code,
using any web framework like Django/Flask, use projects like envparse, using it you can read the value as your defined type.

from envparse import env
# will read WHITE_LIST=hello,world,hi to white_list = ["hello", "world", "hi"]
white_list = env.list("WHITE_LIST", default=[]) 
# Perfect for reading boolean
DEBUG = env.bool("DEBUG", default=False)

NOTE: kennethreitz's autoenv is a recommended tool for making project specific environment variables, please note that those who are using autoenv please keep the .env file private (inaccessible to public)


As for the environment variables:

import os
print os.environ["HOME"]

I'm afraid you'd have to flesh out your second point a little bit more before a decent answer is possible.


The original question (first part) was "how to check environment variables in Python."

Here's how to check if $FOO is set:

try:  
   os.environ["FOO"]
except KeyError: 
   print "Please set the environment variable FOO"
   sys.exit(1)

To check if the key exists (returns True or False)

'HOME' in os.environ

You can also use get() when printing the key; useful if you want to use a default.

print(os.environ.get('HOME', '/home/username/'))

where /home/username/ is the default


For django see (https://github.com/joke2k/django-environ)

$ pip install django-environ

import environ
env = environ.Env(
# set casting, default value
DEBUG=(bool, False)
)
# reading .env file
environ.Env.read_env()

# False if not in os.environ
DEBUG = env('DEBUG')

# Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ
SECRET_KEY = env('SECRET_KEY')

Actually it can be done this away:

import os

for item, value in os.environ.items():
    print('{}: {}'.format(item, value))

Or simply:

for i, j in os.environ.items():
    print(i, j)

For view the value in the parameter:

print(os.environ['HOME'])

Or:

print(os.environ.get('HOME'))

To set the value:

os.environ['HOME'] = '/new/value'