Python: Exporting environment variables in subprocess.Popen(..)

后端 未结 3 1761
死守一世寂寞
死守一世寂寞 2020-11-30 11:06

I am having an issue with setting an environment variable on a call to subprocess.Popen. The environment variable does not seem to be getting set. Any suggestio

相关标签:
3条回答
  • 2020-11-30 11:17

    For Python 3.5 and newer, you can use unpacking generalizations, eg:

    env = {
        **os.environ,
        "TEST_VARIABLE": str(1234),
    }
    subprocess.Popen('/usr/bin/mybinary', env=env).wait()
    
    0 讨论(0)
  • 2020-11-30 11:34

    The substitution of environment variables on the command line is done by the shell, not by /bin/echo. So you need to run the command in a shell to get the substitution:

    In [22]: subprocess.Popen('/bin/echo $TEST_VARIABLE', shell=True, env=d).wait()
    1234
    Out[22]: 0
    

    That doesn't mean the environment variable is not set when shell=False, however. Even without shell=True, the executable does see the enviroment variables set by the env parameter. For example, date is affected by the TZ environment variable:

    In [23]: subprocess.Popen(["date"], env={'TZ': 'America/New_York'}).wait()
    Wed Oct 29 22:05:52 EDT 2014
    Out[23]: 0
    
    In [24]: subprocess.Popen(["date"], env={'TZ': 'Asia/Taipei'}).wait()
    Thu Oct 30 10:06:05 CST 2014
    Out[24]: 0
    
    0 讨论(0)
  • 2020-11-30 11:40

    You should use os.environ.copy() to make it work. It creates a copy of the entire environment dictionary which you can then modify before passing it on to the subprocess, without modifying the current process environment.

    See this answer.

    0 讨论(0)
提交回复
热议问题