Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't Python see environment variables? [duplicate]

I'm working on Debian Jessie with Python 2. Why can't Python's environ see environment variables that are visible in bash?

# echo $SECRET_KEY
xxx-xxx-xxxx
# python
>>> from os import environ
>>> environ["SECRET_KEY"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/root/.virtualenvs/prescribing/lib/python2.7/UserDict.py", line 23, in __getitem__
    raise KeyError(key)
KeyError: 'SECRET_KEY'

I set these environment variables using /etc/environment - not sure if that's relevant:

SECRET_KEY=xxx-xxx-xxx

I had to run source /etc/environment to get bash to see them, which I thought was strange.

UPDATE: printenv SECRET_KEY produces nothing, so I guess SECRET_KEY is a shell not an environment variable.

like image 536
Richard Avatar asked Aug 13 '15 16:08

Richard


People also ask

What is .env file in Python?

A . env file is a text file containing key value pairs of all the environment variables required by your application. This file is included with your project locally but not saved to source control so that you aren't putting potentially sensitive information at risk.

How do I check if an environment variable is set in Python?

getenv() method in Python returns the value of the environment variable key if it exists otherwise returns the default value. default (optional) : string denoting the default value in case key does not exists. If omitted default is set to 'None'.

Where does Python get environment variables from?

To set and get environment variables in Python you can just use the os module: import os # Set environment variables os. environ['API_USER'] = 'username' os. environ['API_PASSWORD'] = 'secret' # Get environment variables USER = os.


1 Answers

You need to export environment variables for child processes to see them:

export SECRET_KEY

Demo:

$ SECRET_KEY='foobar'
$ bin/python -c "import os; print os.environ.get('SECRET_KEY', 'Nonesuch')"
Nonesuch
$ export SECRET_KEY
$ bin/python -c "import os; print os.environ.get('SECRET_KEY', 'Nonesuch')"
foobar

You can combine the setting and exporting in one step:

export SECRET_KEY=xxx-xxx-xxxx

Note that new variables in /etc/environment do not show up in your existing shells automatically, not until you have a new login. For a GUI desktop, you'll have to log out and log in again, for SSH sessions you'll have to create a new SSH login. Only then will you get a new tree of processes with the changes present. Using source /etc/environment only sets 'local' variables (the file is not a script). See How to reload /etc/environment without rebooting? over on Super User.

like image 62
Martijn Pieters Avatar answered Oct 18 '22 20:10

Martijn Pieters