Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 subprocess.run() do work, such as ls and pwd, but not export.

.run() was added in Python 3.5 (in case you didn't recognise it), but I have also tried the above line with .call() and .Popen(), 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 export easier than os.environ.

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

like image 397
99lives Avatar asked Feb 26 '26 06:02

99lives


1 Answers

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.

like image 158
chepner Avatar answered Feb 27 '26 19:02

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!