[Tutor] How to source a shell script through python to set the environment variables.

Aneeque Khan 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 :-
                                                #!/bin/bash
                                                export OS_AK="Aneeque"
export OS_KHAN="KHAN"

echo "Please enter your Stack Password: "
read -sr OS_PWD_INPUT
export OS_PWD=$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 :-
                                                import sys
from pipes import quote
from pprint import pprint

def update_env(script_path):
   if "--child" in sys.argv: # executed in the child environment
      pprint(dict(os.environ))
   else:
      python, script = quote(sys.executable), quote(sys.argv[0])
      os.execl("/bin/bash", "/bin/bash", "-c", "source %s; %s %s --child" % (script_path, python, script))

                                                update_env("env_test.sh")

                with this approach some variables set while others not.

Another approach used :-
def update_env2(script):
    #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()[0]
    #env = dict((line.split("=", 1) for line in output.splitlines()))
    env = dict((line.split("=", 1) for line in output.split('\0')))

    os.environ.update(env)

                                update_env2("env_test.sh")

                this also not provides the desired output.

Regards,
Aneeque


More information about the Tutor mailing list