将 Bash 变量读入 Python 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17435056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:12:27  来源:igfitidea点击:

Read Bash variables into a Python script

pythonbashscriptingenvironment-variables

提问by Tall Paul

I am running a bash script (test.sh) and it loads in environment variables (from env.sh). That works fine, but I am trying to see python can just load in the variables already in the bash script.

我正在运行一个 bash 脚本 (test.sh),它加载到环境变量中(来自 env.sh)。这工作正常,但我试图看到 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

测试文件

#!/bin/bash
source env.sh

echo $test1

python pythontest.py

env.sh

环境文件

#!/bin/bash

test1="hello"

pythontest.py

测试文件

?
print test1 (that is what I want)

采纳答案by AMADANON Inc.

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"]

回答by John

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"]

回答by Taejoon Byun

There's another way using subprocessthat does not depend on setting the environment. With a little more code, though.

还有另一种使用方式subprocess,不依赖于设置环境。不过,多一点代码。

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=Trueshall be set in order to process the shell command in CMDto 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