set environment variables by file using python

Viewed 17298

I have a file contains set of environment variables .

env_script.env:

export a=hjk
export b=jkjk
export c=kjjhh
export i=jkkl
..........

I want set these environment variables by reading from file . how can i do this in python

Tried sample code:

pipe = subprocess.Popen([".%s;env", "/home/user/env_script.env"], stdout=subprocess.PIPE, shell=True)
output = pipe.communicate()[0]
env = dict((line.split("=", 1) for line in output.splitlines()))
os.environ.update(env)

Please give some suggestion

3 Answers

There's a great python library python-dotenv that allows you to have your variables exported to your environment from a .env file, or any file you want, which you can keep out of source control (i.e. add to .gitignore):

# to install
pip install -U python-dotenv
# your .env file
export MY_VAR_A=super-secret-value
export MY_VAR_B=other-very-secret-value
...

And you just load it in python when your start like:

# settings.py
from dotenv import load_dotenv
load_dotenv()

Then, you can access any variable later in your code:

from os import environ

my_value_a = environ.get('MY_VALUE_A')
print(my_value_a) # 'super-secret-value'
Related