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.
subprocess.run(shell=True)starts a new shell. Open two terminals and typeexport FOO=BARin one terminal andecho $FOOin another (the second terminal that runs a separate shell won't see the new$FOOvalue). It is the same reason whycdis a shell builtin (because it changes the working directory of the current process and if it were a separate program thencdwould had to change the environment of the parent process—that can't be done (normally)). See How do I set the working directory of the parent process?