Python:在 subprocess.Popen(..) 中导出环境变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26643719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Exporting environment variables in subprocess.Popen(..)
提问by modulitos
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 suggestions on how to properly set environmental variables for a Python commandline call?
我在调用subprocess.Popen. 环境变量似乎没有设置。关于如何为 Python 命令行调用正确设置环境变量的任何建议?
My goal is to run a script that uses an environmental variable determined from my Python code:
我的目标是运行一个脚本,该脚本使用由我的 Python 代码确定的环境变量:
d = dict(os.environ)
d["TEST_VARIABLE"] = str(1234)
subprocess.Popen('/usr/bin/mybinary', env=d).wait()
but the script reacts as if the variable has never been set
但脚本的反应就像从未设置过变量一样
Here is my attempt to test, using Python's interactive interpreter:
这是我使用 Python 的交互式解释器进行测试的尝试:
d = dict(os.environ)
d["TEST_VARIABLE"] = str(1234)
subprocess.Popen(['/bin/echo', '$TEST_VARIABLE'], env=d).wait()
and the output is:
输出是:
"$TEST_VARIABLE"
0
I thought env=dshould set the environment for the subprocess, but it apparently does not. Any suggestions on how to correct this issue?
我认为env=d应该为子流程设置环境,但显然没有。有关如何解决此问题的任何建议?
采纳答案by unutbu
The substitution of environment variables on the command lineis done by the shell, not by /bin/echo. So you need to run the command in a shell to get the substitution:
命令行上环境变量的替换是由 shell 完成的,而不是由 /bin/echo 完成的。所以你需要在 shell 中运行命令来获取替换:
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 envparameter. For example, dateis affected by the TZenvironment variable:
然而,这并不意味着当 时未设置环境变量shell=False。即使没有shell=True,可执行文件也会看到env参数设置的环境变量。比如date受TZ环境变量影响:
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
回答by Avinash Babu
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.
你应该用os.environ.copy()它来让它工作。它创建整个环境字典的副本,然后您可以在将其传递给子进程之前对其进行修改,而无需修改当前进程环境。
See this answer.
看到这个答案。
回答by ideasman42
For Python 3.5 and newer, you can use unpacking generalizations, eg:
对于 Python 3.5 及更新版本,您可以使用解包概括,例如:
env = {
**os.environ,
"TEST_VARIABLE": str(1234),
}
subprocess.Popen('/usr/bin/mybinary', env=env).wait()

