Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load environment variables from a shell script

I have a file with some environment variables that I want to use in a python script

The following works form the command line

$ source myFile.sh
$ python ./myScript.py

and from inside the python script I can access the variables like

import os
os.getenv('myvariable')

How can I source the shell script, then access the variables, from with the python script?

like image 287
lafferc Avatar asked Jun 29 '15 13:06

lafferc


People also ask

How are environment variables accessed in a shell script?

Shell variables are only present in the shell in which they were defined. Environment variables are inherited by child shells but shell variables are not. Shell variable can be made an environment variable by using export command. A script is simply a collection of commands that are intended to run as a group.

How do I pass an environment variable in bash script?

Environment Variables Bash scripts can also be passed with the arguments in the form of environment variables. This can be done in either of the following ways: Specifying the variable value before the script execution command. Exporting the variable and then executing the script.


1 Answers

If you are saying backward environment propagation, sorry, you can't. It's a security issue. However, directly source environment from python is definitely valid. But it's more or less a manual process.

import subprocess as sp

SOURCE = 'your_file_path'
proc = sp.Popen(['bash', '-c', 'source {} && env'.format(SOURCE)], stdout=sp.PIPE)

source_env = {tup[0].strip(): tup[1].strip() for tup in map(lambda s: s.strip().split('=', 1), proc.stdout)}

Then you have everything you need in source_env.

If you need to write it back to your local environment (which is not recommended, since source_env keeps you clean):

import os

for k, v in source_env.items():
    os.environ[k] = v

Another tiny attention needs to be paid here, is since I called bash here, you should expect the rules are applied here too. So if you want your variable to be seen, you will need to export them.

export VAR1='see me'
VAR2='but not me'
like image 198
Jason Hu Avatar answered Sep 25 '22 21:09

Jason Hu