[Tutor] How to source a shell script through python to set the environment variables.
aneeque.khan at ericsson.com
Tue Feb 23 02:29:51 EST 2016
>From the past week I am struggling to source a shell script through python script, to set the environment variables. Problem details are :-
I have a shell script named "env_test.sh", through which I set some environment variables by using command "source env_test.sh".
env_test.sh looks like this :-
echo "Please enter your Stack Password: "
read -sr OS_PWD_INPUT
Now I want to execute the above script through python file named "ak_test.py", to set these variables and access them further in the code.
First I tried to this way :-
subprocess.call(". env_test.sh; env|grep OS_", shell=True, executable="/bin/bash")
above command opens up new process and sets the environment for that process only due to this updated environment doesn`t reflect to the main process.
After this I tried to do this way :-
from pipes import quote
from pprint import pprint
if "--child" in sys.argv: # executed in the child environment
python, script = quote(sys.executable), quote(sys.argv)
os.execl("/bin/bash", "/bin/bash", "-c", "source %s; %s %s --child" % (script_path, python, script))
with this approach some variables set while others not.
Another approach used :-
#pipe1 = subprocess.Popen(". %s; env -0" % script, stdout=subprocess.PIPE, shell=True, executable="/bin/bash")
pipe1 = subprocess.Popen(". %s; env" % script, stdout=subprocess.PIPE, shell=True, executable="/bin/bash")
output = pipe1.communicate()
#env = dict((line.split("=", 1) for line in output.splitlines()))
env = dict((line.split("=", 1) for line in output.split('\0')))
this also not provides the desired output.
More information about the Tutor