7

In python, is there a way to retrieve the value of an env variable from a specific .env file? For example, I have multiple .env files as follows:

.env.a .env.a ...

And I have a variable in .env.b called INDEX=4.

I tried receiving the value of INDEX by doing the following:

import os

os.getenv('INDEX')

But this value returns None.

Any suggestions?

swing1234
  • 233
  • 1
  • 3
  • 13
  • It might be easier if you do something like `os.environ['INDEX'] = '4'` in your `*.py` file – vlovero Jul 21 '20 at 17:07
  • 1
    There is no built-in support for .env files in python. But you could use a package like `python-dotenv` that can add support for those. https://pypi.org/project/python-dotenv/ – Jonas Jul 21 '20 at 17:08

3 Answers3

7

This is a job for ConfigParser or ConfigObj. ConfigParser is built into the Python standard library, but has the drawback that it REALLY wants section names. Below is for Python3. If you're still using Python2, then use import ConfigParser

import configparser
config = configparser.ConfigParser()
config.read('env.b')
index = config['mysection']['INDEX']

where env.b for ConfigParser is

[mysection]
INDEX=4

And using ConfigObj:

import configobj
config = configobj.ConfigObj('env.b')
index = config['INDEX']

where env.b for ConfigObj is

INDEX=4
bfris
  • 5,272
  • 1
  • 20
  • 37
  • I am getting 'keyerror' when I use config parser in the way you described – swing1234 Jul 21 '20 at 20:43
  • I had an error in my import statement and some extra spaces. I've edited my answer. 'key error', however, points to a typo in your code or env.b file. Python is case sensitive. – bfris Jul 21 '20 at 21:14
  • Does 'env.b' have to be in the same directory as the file you are running the code from? My env.b is 3 directories above. In that case, do I have to specify like, config.read(/path/to/env/env.b)? – swing1234 Jul 21 '20 at 22:35
  • You'll have to either specify absolute path (/path/to/env/env.b) or relative path (../../../env3). I just did a test on Windows and relative path works. You need ` ../ ` for every directory up you want to go. – bfris Jul 22 '20 at 00:29
7

Python has a specific package named python-dotenv to use keys stored in the .env file. Here is how we can use a key in the .env file. First, create a key like this in the .env file

demokey=aaa2134

To load this key in the python file we can use this code:

from dotenv import load_dotenv
load_dotenv()
import os
x = os.getenv("demokey")
print(x)

In Python 3.x , since its not available natively

pip install python-dotenv
arun-r
  • 3,104
  • 2
  • 22
  • 20
SYED FAISAL
  • 495
  • 5
  • 8
1

You can use the environs library and os library to pull from .env files.

Would look something like:

import os
from environs import Env

env = Env()
env.read_env() # read .env file, if it exists

os.getenv("TEST_API_KEY")
Hofbr
  • 868
  • 9
  • 31