Stack Overflow Asked by swing1234 on November 10, 2021
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?
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)
Answered by SYED FAISAL on November 10, 2021
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
Answered by bfris on November 10, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP