Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Get value of env variable from a specific .env file

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?

like image 323
swing1234 Avatar asked Jun 08 '26 07:06

swing1234


1 Answers

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
like image 133
bfris Avatar answered Jun 10 '26 20:06

bfris