简体   繁体   English

将 Bash 变量读入 Python 脚本

[英]Read Bash variables into a Python script

I am running a bash script (test.sh) and it loads in environment variables (from env.sh).我正在运行一个 bash 脚本(test.sh),它加载到环境变量中(来自 env.sh)。 That works fine, but I am trying to see python can just load in the variables already in the bash script.这很好,但我试图看到 python 可以加载已经在 bash 脚本中的变量。

Yes I know it would probably be easier to just pass in the specific variables I need as arguments, but I was curious if it was possible to get the bash variables.是的,我知道将我需要的特定变量作为参数传递可能会更容易,但我很好奇是否可以获取 bash 变量。

test.sh测试.sh

#!/bin/bash
source env.sh

echo $test1

python pythontest.py

You need to export the variables in bash, or they will be local to bash:您需要在 bash 中导出变量,否则它们将是 bash 的本地变量:

export test1

Then, in python然后,在蟒蛇

import os
print os.environ["test1"]

There's another way using subprocess that does not depend on setting the environment.还有另一种使用subprocess ,它不依赖于设置环境。 With a little more code, though.不过,多一点代码。

For a shell script that looks like follows:对于如下所示的 shell 脚本:

#!/bin/sh
myvar="here is my variable in the shell script"

function print_myvar() {
    echo $myvar
}

You can retrieve the value of the variable or even call a function in the shell script like in the following Python code:您可以检索变量的值,甚至可以在 shell 脚本中调用函数,如下面的 Python 代码所示:

import subprocess

def get_var(varname):
    CMD = 'echo $(source myscript.sh; echo $%s)' % varname
    p = subprocess.Popen(CMD, stdout=subprocess.PIPE, shell=True, executable='/bin/bash')
    return p.stdout.readlines()[0].strip()

def call_func(funcname):
    CMD = 'echo $(source myscript.sh; echo $(%s))' % funcname
    p = subprocess.Popen(CMD, stdout=subprocess.PIPE, shell=True, executable='/bin/bash')
    return p.stdout.readlines()[0].strip()

print get_var('myvar')
print call_func('print_myvar')

Note that both shell=True shall be set in order to process the shell command in CMD to be processed as it is, and set executable='bin/bash' to use process substitution, which is not supported by the default /bin/sh .注意, shell=True需要设置,以便处理CMD中的 shell 命令按原样处理,设置executable='bin/bash'使用进程替换,默认/bin/sh不支持.

Assuming the environment variables that get set are permanent, which I think they are not.假设设置的环境变量是永久性的,我认为它们不是。 You can use os.environ .您可以使用os.environ

os.environ["something"]

I created a little library that does this: 我创建了一个这样做的小库:

https://github.com/aneilbaboo/shellvars-py https://github.com/aneilbaboo/shellvars-py

If you are trying to source a file, the thing you are missing is set -a .如果您尝试获取文件的来源,则缺少的内容是set -a For example, to source env.sh , you would run:例如,要获取env.sh ,您可以运行:

set -a; source env.sh; set +a.

The reason you need this is that bash's variables are local to bash unless they are exported.您需要这样做的原因是 bash 的变量对于 bash 来说是本地的,除非它们被导出。 The -a option instructs bash to export all new variables (until you turn it off with +a). -a 选项指示 bash 导出所有新变量(直到您使用 +a 将其关闭)。 By using set -a before source , all of the variables imported by source will also be exported, and thus available to python.通过在source之前使用set -a ,所有由source导入的变量也将被导出,因此可用于 python。

Credit: this command comes from a comment posted by @chepner as a comment on this answer .信用:此命令来自@chepner 作为对此答案的评论发布的评论。

Two additional options, which may or may not help in your specific situation:两个附加选项,在您的特定情况下可能会或可能不会有帮助:

Option 1:选项1:

if env.sh only contains regular NAME=value, get python to read it (as a text file) instead.如果 env.sh 仅包含常规 NAME=value,则让 python 读取它(作为文本文件)。

This only applies if you control the format of env.sh, and env.sh doesn't contain any real shell commands, and you control the containing shell script.这仅适用于您控制 env.sh 的格式,并且 env.sh 不包含任何真正的 shell 命令,并且您控制包含的 shell 脚本的情况。

Option 2:选项 2:

In the shell script, once all the necessary variables are set, either save these to a file, or pipe them as stdin to your python script:在 shell 脚本中,一旦设置了所有必要的变量,要么将它们保存到文件中,要么将它们作为标准输入通过管道传输到 python 脚本:

#!/bin/bash
source env.sh

echo $test1

set | python pythontest.py

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

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