Zoron
Zoron

Reputation: 11

Unable to read Environmental Variable in Python

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

  1. I stored the value in the Environmental Variable using :
export KEY123=xxx123xxxABCxxx789
  1. In python (Flask application) I'm trying to read the value using the following code :
import os 
app.config['KEY'] = os.environ['KEY123']
  1. When I run my script I'm getting the error :
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

Answers (4)

Ruta Deshpande
Ruta Deshpande

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

Anıl
Anıl

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

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

al76
al76

Reputation: 764

python-dotenv https://github.com/theskumar/python-dotenv#readme will manage your environment vars.

Upvotes: 0

Related Questions