Start subprocess with environment variables

Viewed 503

I need to start a process where I pass some parameters to the sub-process in environment variables.

I know I can use subprocess.run() to do this in python > 3.5. How can I do it with python 2.7 ?

In python 2.7 I can modify the environment variables of the process that start the sub-process. The sub-process will inherit the environment variables. But I don’t want that. I want to set the environment variables only in the sub-process.

1 Answers

Use: subprocess.Popen('env', env={'A':'5','B':'5'})

Sample run:

>>> import subprocess
>>> subprocess.Popen('env', env={'A':'5','B':'5'})
<subprocess.Popen object at 0x102288950>
>>> A=5
B=5

From the docs:

If env is not None, it must be a mapping that defines the environment variables for the new process; these are used instead of inheriting the current process’ environment, which is the default behavior.

Python3 subprocess.run() is using the same Popen kwarg env:

The full function signature is largely the same as that of the Popen constructor

Related