Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set environment variables by file using python

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

like image 647
user092 Avatar asked May 12 '17 09:05

user092


2 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'
like image 151
juanesarango Avatar answered Sep 29 '22 11:09

juanesarango


You don't need to use subprocess.

Read lines and split environment variable name, value and assign it to os.environ:

import os

with open('/home/user/env_script.env') as f:
    for line in f:
        if 'export' not in line:
            continue
        if line.startswith('#'):
            continue
        # Remove leading `export `
        # then, split name / value pair
        key, value = line.replace('export ', '', 1).strip().split('=', 1)
        os.environ[key] = value

or using dict.update and generator expression:

with open('env_script.env') as f:
    os.environ.update(
        line.replace('export ', '', 1).strip().split('=', 1) for line in f
        if 'export' in line
    )

Alternatively, you can make a wrapper shell script, which sources the env_script.env, then execute the original python file.

#!/bin/bash
source /home/user/env_script.env
python /path/to/original_script.py
like image 34
falsetru Avatar answered Sep 29 '22 12:09

falsetru