2777

How do I get the value of an environment variable in Python?

Mateen Ulhaq
  • 21,459
  • 16
  • 82
  • 123
Amit Yadav
  • 28,830
  • 6
  • 40
  • 52

15 Answers15

4035

Environment variables are accessed through os.environ:

import os
print(os.environ['HOME'])

To see a list of all environment variables:

print(os.environ)

If a key is not present, attempting to access it will raise a KeyError. To avoid this:

# Returns `None` if key doesn't exist
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))

# Returns `default_value` if key doesn't exist
print(os.environ.get('KEY_THAT_MIGHT_EXIST', default_value))

# Returns `default_value` if key doesn't exist
print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))
Mateen Ulhaq
  • 21,459
  • 16
  • 82
  • 123
Rod
  • 48,232
  • 3
  • 34
  • 52
  • 1
    hello rod, thanks for your effective reply concerning 'default-installation'; effective in point of view to understand it quickly rather than go through the links. That’s really I appreciated :) but about my (1) question please look at the command and outputs snippet below: >>> import os >>> print os.environ['PYTHONPATH'] Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\os.py", line 435, in __getitem__ return self.data[key.upper()] KeyError: 'PYTHONPATH' >>> print os.environ.get('PYTHONPATH') None >>> // PLZ to be continue...// – Amit Yadav Feb 05 '11 at 14:47
  • In a 1st way script is throwing Exception whereas with 2nd one giving None. So, is there any way to get it meaningful value or am I doing in a wrong way??? Amit. – Amit Yadav Feb 05 '11 at 14:49
  • 9
    os.environ is a dictionary. Trying to access a key not present in the dictionary will throw a KeyError. The get method simply returns None when the key does not exists. Do you have PYTHONPATH set? Can you try with a variable such as PATH, that is guaranteed to exist? Does it return a meaningful value? – Rod Feb 05 '11 at 19:21
  • I haven’t set it (PYTHONPATH) before; what I am doing just go with command prompt and type CMD anywhere (since python.exe is in my shell PATH). If I try to access Window ENVIRONMENT variable, it gives mapped value but the problem with Python ENVIRONMENT variable like; PYTHONPATH and PYTHONHOME. – Amit Yadav Feb 07 '11 at 08:02
  • 2
    PYTHONPATH is used to add new search path to Python (sys.path) from outside Python. Have a look at http://docs.python.org/using/cmdline.html#environment-variables – Rod Feb 07 '11 at 14:41
  • Is there any way to keep this variable persistent ?? When I run python later on the environment variable is gone and gives a `raise KeyError(key)` instead – mrid Jan 29 '17 at 07:29
  • @mrid There is no direct way from python to persist the environment variable. On windows you can write them in the registry, on Linux/OSX you might have to change you environment using scripts. – Rod Jan 31 '17 at 14:04
  • is this a portable solution? – Charlie Parker May 09 '17 at 20:48
  • @CharlieParker Yes, as far as I know, it is portable. – Rod May 12 '17 at 19:00
  • 31
    `.get()` can also be given a default. – Gringo Suave Sep 21 '18 at 15:25
  • For checking whether a environmental variable is set to some value, try: `if getenv('your_variable') == 'your value':` – RicarHincapie Aug 13 '20 at 16:02
313

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

Boris Verkhovskiy
  • 10,733
  • 7
  • 77
  • 79
lgriffiths
  • 3,275
  • 1
  • 12
  • 7
  • 4
    Which is better, `"HOME" in os.environ` or `os.environ.get('HOME')`? – endolith Feb 03 '17 at 16:11
  • 14
    @endolith They do different things. The first returns True or False, while the second returns a value, possibly None. – Trenton Feb 13 '18 at 22:38
  • 3
    @endolith, the correct question woud be `"HOME" in os.environ` vs `os.environ.get('HOME') is None`. As you can see first is far more readable & comfortable to work with. – Konstantin Sekeresh Oct 16 '19 at 13:43
73

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)
Mateen Ulhaq
  • 21,459
  • 16
  • 82
  • 123
Scott C Wilson
  • 17,826
  • 10
  • 57
  • 80
  • 5
    Try can be faster. The case of env vars is likely best for 'try': http://stackoverflow.com/a/1835844/187769 – RandomInsano Feb 05 '17 at 16:49
  • 24
    @RandomInsano faster =/= better. This code looks less readable than an `"if 'FOO' not in os.environ: ..."` block – Dangercrow Oct 13 '17 at 13:27
72

Actually it can be done this way:

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 viewing the value in the parameter:

print(os.environ['HOME'])

Or:

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

To set the value:

os.environ['HOME'] = '/new/value'
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
britodfbr
  • 1,495
  • 12
  • 16
  • 8
    No, this answer really doesn't add anything on top of the existing answers – Bart May 02 '18 at 10:06
  • 2
    This should be removed, it is a duplicate of other answers. `str.format` is just a fancy addition. – miike3459 Apr 21 '19 at 16:46
  • `>>> import os, pprint; pprint.pprint(list(os.environ.items()))` – noobninja May 10 '20 at 18:41
  • 1
    The first answer with readable output for the entire env, thanks. To view the env in the PyCharm debugger, I evaluate `{k: v for k,v in sorted(os.environ.items())}` – Noumenon Aug 04 '21 at 22:55
  • it adds how to set the value – M.C. Nov 26 '21 at 10:21
  • I have to agree. Seems like a duplicate answer. Setting the environment variable is not new information pertaining to the question. I'd also say setting the environment variable in python is 9 times out of 10 not the approach you are wanting since environment variables are really meant to keep things out of the code repository as they vary by environment. – Kolton Noreen Dec 22 '21 at 18:41
58

You can access the environment variables using

import os
print os.environ

Try to see the content of the PYTHONPATH or PYTHONHOME environment variables. Maybe this will be helpful for your second question.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
andrei1089
  • 988
  • 5
  • 8
35

As for the environment variables:

import os
print os.environ["HOME"]
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Jim Brissom
  • 30,045
  • 3
  • 35
  • 33
30
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.

erik.weathers
  • 759
  • 1
  • 7
  • 13
Azorian
  • 301
  • 3
  • 2
27

Import the os module:

import os

To get an environment variable:

os.environ.get('Env_var')

To set an environment variable:

# Set environment variables
os.environ['Env_var'] = 'Some Value'
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
imerla
  • 1,496
  • 2
  • 12
  • 18
23

If you are planning to use the code in a production web application code, using any web framework like Django and 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. For those who are using autoenv, please note to keep the .env file private (inaccessible to public).

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Renjith Thankachan
  • 3,896
  • 1
  • 25
  • 44
14

There are 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']
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Peter Konneker
  • 153
  • 1
  • 7
  • 1
    What does "rad" mean in *"which is rad"*? *[rad](https://en.wiktionary.org/wiki/rad#Adjective)* - *"1. (slang) Clipping of radical; excellent"* – Peter Mortensen Jul 25 '21 at 21:06
8

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 environment variable

SECRET_KEY=config('SECRET_KEY')

Read more about the Python library here.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Steve Mitto
  • 113
  • 1
  • 5
7

Edited - October 2021

Following @Peter's comment, here's how you can test it:

main.py

#!/usr/bin/env python


from os import environ

# Initialize variables
num_of_vars = 50
for i in range(1, num_of_vars):
    environ[f"_BENCHMARK_{i}"] = f"BENCHMARK VALUE {i}"  

def stopwatch(repeat=1, autorun=True):
    """
    Source: https://stackoverflow.com/a/68660080/5285732
    stopwatch decorator to calculate the total time of a function
    """
    import timeit
    import functools
    
    def outer_func(func):
        @functools.wraps(func)
        def time_func(*args, **kwargs):
            t1 = timeit.default_timer()
            for _ in range(repeat):
                r = func(*args, **kwargs)
            t2 = timeit.default_timer()
            print(f"Function={func.__name__}, Time={t2 - t1}")
            return r
        
        if autorun:
            try:
                time_func()
            except TypeError:
                raise Exception(f"{time_func.__name__}: autorun only works with no parameters, you may want to use @stopwatch(autorun=False)") from None
        
        return time_func
    
    if callable(repeat):
        func = repeat
        repeat = 1
        return outer_func(func)
    
    return outer_func

@stopwatch(repeat=10000)
def using_environ():
    for item in environ:
        pass

@stopwatch
def using_dict(repeat=10000):
    env_vars_dict = dict(environ)
    for item in env_vars_dict:
        pass
python "main.py"

# Output
Function=using_environ, Time=0.216224731
Function=using_dict, Time=0.00014206099999999888

If this is true ... It's 1500x faster to use a dict() instead of accessing environ directly.


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.

Meir Gabay
  • 2,150
  • 1
  • 21
  • 28
4

For Django, see 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')
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Leonardo
  • 194
  • 1
  • 5
  • 1
    An explanation would be in order. What is the context - in what context is the code executed? On a server with Django? Locally for testing it out? Somewhere else? What is the idea? What is the code supposed to accomplish? – Peter Mortensen Jul 25 '21 at 21:11
1

You should first import os using

import os

and then actually print the environment variable value

print(os.environ['yourvariable'])

of course, replace yourvariable as the variable you want to access.

ichirod
  • 183
  • 1
  • 4
1

The tricky part of using nested for-loops in one-liners is that you have to use list comprehension. So in order to print all your environment variables, without having to import a foreign library, you can use:

python -c "import os;L=[f'{k}={v}' for k,v in os.environ.items()]; print('\n'.join(L))"
not2qubit
  • 11,992
  • 7
  • 83
  • 112