Python:在subprocess.Popen(..)中导出环境变量 [英] Python: Exporting environment variables in subprocess.Popen(..)
问题描述
我在调用 subprocess.Popen
时设置一个环境变量有问题。环境变量似乎没有被设置。关于如何正确设置Python命令行调用的环境变量的任何建议?
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?
我的目标是运行一个使用从我的Python代码确定的环境变量的脚本: p>
My goal is to run a script that uses an environmental variable determined from my Python code:
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
这是我尝试使用Python的交互式解释器进行测试:
Here is my attempt to test, using Python's interactive interpreter:
d = dict(os.environ)
d["TEST_VARIABLE"] = str(1234)
subprocess.Popen(['/bin/echo', '$TEST_VARIABLE'], env=d).wait()
,输出为:
"$TEST_VARIABLE"
0
我以为 env = d
应该为子进程设置环境,但是显然没有。关于如何纠正这个问题的任何建议?
I thought env=d
should set the environment for the subprocess, but it apparently does not. Any suggestions on how to correct this issue?
推荐答案
在命令行上替换环境变量由shell完成,而不是由/斌/回声。所以你需要在一个shell中运行命令来获得替换:
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
然而,这并不意味着环境变量在 shell = False
时未设置。即使没有 shell = True
,可执行文件也会看到由 env
参数设置的环境变量。例如, date
受 TZ
环境变量的影响:
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
这篇关于Python:在subprocess.Popen(..)中导出环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!