Calling the source command from subprocess.popen to update the os.environ.

Ben Finney ben+python at benfinney.id.au
Sun Mar 27 09:59:58 EDT 2016


Hongyi Zhao <hongyi.zhao at gmail.com> writes:

> I use the following code the update the os.environ:
>
> import os
> from subprocess import check_output
>
> # POSIX: name shall not contain '=', value doesn't contain '\0'
> output = check_output("source /home/werner/env-intel-toolchains.sh;
>          env -0", shell=True, executable="/bin/bash")

That will start a new process (running ‘/bin/bash’), then execute some
commands from a script file in that process.

When that new process ends, any changes in its environment also
disappear.

At no point do changes to that new process's environment have any effect
on the Python process.

A Unix process is *completely unable* to change the environment
variables of its parent. It can change its own variables, and optionally
those of its child processes.

This is by design. It's a good thing.

So if you want the Python process's environment to change, then it needs
to be:

* Inherited from an *already* changed environment when it starts.

Or:

* Changed within the Python process, by the Python API for that purpose
  (‘os.environ’).

You will not be able to change a Python process environment by starting
new processes.

-- 
 \       “Faith, n. Belief without evidence in what is told by one who |
  `\   speaks without knowledge, of things without parallel.” —Ambrose |
_o__)                           Bierce, _The Devil's Dictionary_, 1906 |
Ben Finney




More information about the Python-list mailing list