I set an environment variable that I want to access in my Python application. How do I get its value?
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')
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
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.
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.
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.