How do I access environment variables from Python?

Amit Yadav Source

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

pythonenvironment-variables

Answers

answered 8 years ago andrei1089 #1

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.

answered 8 years ago Jim Brissom #2

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.

answered 8 years ago Rod #3

Environment variables are accessed through os.environ

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

Or you can see a list of all the environment variables using:

os.environ

As sometimes you might need to see a complete list!

# using get will return `None` if a key is not present rather than raise a `KeyError`
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))

# os.getenv is equivalent, and can also give a default value instead of `None`
print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))

Python default installation on Windows is C:\Python. If you want to find out while running python you can do:

import sys
print(sys.prefix)

answered 6 years ago Scott C Wilson #4

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)

answered 6 years ago lgriffiths #5

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

"HOME" in os.environ

or (removed from python 3.x)

os.environ.has_key("HOME")

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

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

where /home/username/ is the default

answered 2 years ago I Am Batman #6

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)

answered 1 year ago Azorian #7

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.

answered 7 months ago Kardi Teknomo #8

In Python 3:

#!/usr/bin/python3
import os
for param in os.environ.keys():
    print("%s: %s " % (param, os.environ[param]))

answered 7 months ago britodfbr #9

Actualy may be this away:

import os

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

Or simplely:

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'

answered 6 months ago pudepied #10

Here is a one-line option assuming import os has been done:

for key in os.environ: print(key,':',os.environ[key])

or with formatting:

for key in os.environ: print('{:>30} {:<4} {:}'.format(key,':',os.environ[key]))

answered 1 month ago crifan #11

for os.environ.get:

try:  
   env_value = os.environ.get("key_maybe_not_exist")
except KeyError: 
   print("Not exist environment value for %s" % "key_maybe_not_exist")

or:

if "key_maybe_not_exist" in os.environ:
    existed_env_value = os.environ["key_maybe_not_exist"]

for os.getenv:

existed_env_value = os.getenv("key_maybe_not_exist")

equivalent to:

existed_env_value = os.getenv("key_maybe_not_exist", default=None)

comments powered by Disqus