Python 2.7保留子进程的env变量

时间:2015-08-19 12:23:54

标签: python bash python-2.7 variables subprocess

我正在调用一个导出一些变量的bash脚本,一旦我尝试将args添加到我的bash脚本中,我找到了获取这些变量的方法并且它正常工作它失败了。 这是我的python脚本的一部分:

bash_script = "./testBash.sh"
script_execution = Popen(["bash", "-c", "trap 'env' exit; source \"$1\"  > /dev/null 2>&1",

                                  "_", bash_script], shell=False, stdout=PIPE)
err_code = script_execution.wait()
variables = script_execution.communicate()[0]

这是我的示例Bash脚本:

export var1="test1"

export var2=$var1/test2

echo "this is firsr var: var1=$var1"
echo "this is the second var: var2=$var2"

bash_script = "./testBash.sh"更改为bash_script = "./testBash.sh test test"后 我没有将导出的变量从bash脚本返回到Python脚本中的variables变量中。 上面提供的是一个示例,当然我的真实脚本要大得多。

1 个答案:

答案 0 :(得分:1)

如果您将bash_script = "./testBash.sh"更改为bash_script = "./testBash.sh test test",则bash_script的名称将更改为"./testBash.sh test test"'test test'不会被解释为单独的参数。

相反,将额外的参数添加到传递给Popen的列表中:

bash_script = "./testBash.sh"
script_execution = Popen(
["bash", "-c", "trap 'env' exit; source \"$1\"  > /dev/null 2>&1",
 "_", bash_script, 'test', 'test'], shell=False, stdout=PIPE)

然后err_code将为0(表示成功),而不是1.从您发布的代码中不清楚您想要发生什么。额外的test参数将被忽略。

但是,bash脚本会收到额外的参数。如果你把它放在

export var1="$2"
testBash.sh

,然后variables(在Python脚本中)将包含

var1=test

您可能还会发现使用

更方便
import subprocess
import os

def source(script, update=True):
    """
    http://pythonwise.blogspot.fr/2010/04/sourcing-shell-script.html (Miki Tebeka)
    http://stackoverflow.com/a/20669683/190597 (unutbu)
    """
    proc = subprocess.Popen(
        ". %s; env -0" % script, stdout=subprocess.PIPE, shell=True)
    output = proc.communicate()[0]
    env = dict((line.split("=", 1) for line in output.split('\x00') if line))
    if update:
        os.environ.update(env)
    return env

bash_script = "./testBash.sh"
variables = source(bash_script)
print(variables)

产生环境变量

{ 'var1': 'test1', 'var2': 'test1/test2', ... }

在一个词典中。