Reputation: 11
Unable to read an environmental variable using Python. I'm using Flask and would like to use a Key whose value is stored in an environmental variable.
I stored my key using the export command, and tried to read the value using the key in python using the OS Module
export KEY123=xxx123xxxABCxxx789
import os
app.config['KEY'] = os.environ['KEY123']
File ".../2.7/lib/python2.7/UserDict.py", line
23, in __getitem__
raise KeyError(key)
KeyError: 'KEY123'
What exactly is done wrong here.
P.S : If I print the value in my commandline using
print(os.environ['KEY123']), it works!
The Environmental variable is not present if I print using 'printenv' in other terminals. I'm doing this to avoid accidental commits to repositories
Upvotes: 0
Views: 3332
Reputation: 213
If you are trying to set environment variable in Windows, then you can use
set KEY123=xxx123xxxABCxxx789
or you can also set variables in
Control Panel\System and Security\System\Advanced system settings\Environment Variables and then add new variable.
If required restart your server/console once.
Upvotes: 0
Reputation: 136
An environment variable is a variable passed through the application from outside of the application context. Common use cases for environment varibles are passing api keys, urls, configs etc. to the application.
In python, luckily we have virtual environments. A virtual environment is an isolated space to have application related depencies. Also, a virtual environment can have its environment variables.
In the activate
file of your virtual environment you can set your environment variables and whenever you run your application within this environment your your varibles will be read from there.
# PATH-TO_VENV/bin/activate
KEY123=xxx123xxxABCxxx789
On the other hand, just in case of using an IDE to run your python program, there should be option in run configurations to be able to add environmental varibles.
Upvotes: 1
Reputation: 419
the command export
set the variable for the current shell and all processes started from current shell :
export KEY123=xxx123xxxABCxxx789
To set it permanently, and system wide (all users, all processes) add set variable in /etc/environment
:
sudo -H gedit /etc/environment
and add the variable you want to access to this file like :
KEY123=xxx123xxxABCxxx789
Do not use the export
keyword here.
You need to logout from current user and login again so environment variables changes take place.
Upvotes: 1
Reputation: 764
python-dotenv https://github.com/theskumar/python-dotenv#readme
will manage your environment vars.
Upvotes: 0