99lives 99lives - 1 year ago 38
Python Question

Running 'export' command with Pythons 'subprocess' does not work

subprocess.run('export FOO=BAR', shell=True)

This simply doesn't work, and I have no idea why.

All I am trying to do I set an environment variable from my python (3.5.1) script, and when I run the above line, nothing happens. No errors are raised, and when I check the environment variable myself, it has not been set.

Other shell commands with
do work, such as
, but not

was added in Python 3.5 (in case you didn't recognise it), but I have also tried the above line with
, with no change in results.

I am aware that I can set environment variables in python with
os.environ['FOO'] = "BAR"
, but I will be using shell commands a lot in my project, and I expect that I will need to string multiple commands together, which will make using
easier than

My project will run on Linux, which is what my machine is running on.


It works fine; however, the variable setting only exists in the subprocess. You cannot affect the environment of the local process from a child.

os.environ is the correct solution, as it changes the environment of the local process, and those changes will be inherited by any process started with subprocess.run.

You can also use the env argument to run:

subprocess.run(["cmdname", "arg1", "arg number 2"], env=dict(FOO='BAR', **os.environ))

This runs the command in a modified environment that includes FOO=BAR without modifying the current environment.