Python:在 subprocess.Popen(..) 中导出环境变量 [英] Python: Exporting environment variables in subprocess.Popen(..)

查看:42
本文介绍了Python:在 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 代码确定的环境变量:

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 完成的,而不是由/bin/echo 完成的.所以你需要在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 参数设置的环境变量.例如,dateTZ 环境变量的影响:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆