繁体   English   中英

Python 2.7保留子进程中的env变量

[英]Python 2.7 keep env variables from a 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变量。 上面提供的是一个示例,当然我的真实脚本要大得多。

如果将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', ... }

在一个字典中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM