Search code examples
pythonsubprocesspopen

Python2.7 subprocess32: how to share environment between two scripts executed via Popen?


I have 2 scripts: 1. Config one, which modifies about 20 environment variables and runs another small script inside, and 2. The process one which uses environment variables set by script1 to do something.

I tried to execute them one by one via Python2.7 subprocess32.Popen() and pass the same env variable to both Popen. No success, environments from script1 are just empty for script2

import os
import subprocess32 as subprocess
my_env = os.environ
subprocess.Popen(script1, env=my_env)
subprocess.Popen(script2, env=my_env)

How I could actually share environment between 2 scripts?


Solution

  • When the first subprocess exits, the changes to its environment are gone. Such changes are only propagated to its own subprocess. You need to do something like this:

    import shlex
    
    subprocess.Popen(". {}; {}".format(shlex.quote(script1),
                                       shlex.quote(script2)), 
                     shell=True)
    

    But as always, using shell=True can introduce security issues.