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

Alan Gauld alan.gauld at btinternet.com
Tue Feb 23 05:46:25 EST 2016


On 23/02/16 07:29, Aneeque Khan wrote:

> 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.

Can I first ask why you are trying to do it via a shell
script rather than using Python directly? Is this part
of a bigger workflow?

The problem is that virtually any method of running
a shell script will involve starting a separate process
and setting the variables in that process' environment.

So far as I can tell the only way to do what you want
would be to run your shell script first then launch
your python script from the shell script. That would
mean breaking your current python script in two, and
if you do a lot of work prior to launching the shell,
that's probably not practical.


> 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))
> 
> with this approach some variables set while others not.

That surprises me since calling execl() overwrites the calling
process with the called process, so I would not expect you
to see anything in your calling script.

How are you testing the results?
Are you checking os.environ?
Or are you using os.getenv()?

> 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)

While this could work you are not really reading the environment
variables you are simply reading the stdout. You could achieve
the same by parsing the script as a text file.

So can you explain why you need to load these values from a
shell script rather than setting os.environ directly?
Maybe we can solve the bigger issue.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list