Tal*_*aul 39 python bash scripting environment-variables
我正在运行一个bash脚本(test.sh),它加载到环境变量(来自env.sh).这工作正常,但我试图看到python可以加载已经在bash脚本中的变量.
是的我知道传递我需要的特定变量作为参数可能更容易,但我很好奇是否有可能获得bash变量.
test.sh
#!/bin/bash
source env.sh
echo $test1
python pythontest.py
Run Code Online (Sandbox Code Playgroud)
env.sh
#!/bin/bash
test1="hello"
Run Code Online (Sandbox Code Playgroud)
pythontest.py
?
print test1 (that is what I want)
Run Code Online (Sandbox Code Playgroud)
AMA*_*nc. 54
你需要在bash中导出变量,或者它们是bash的本地变量:
export test1
Run Code Online (Sandbox Code Playgroud)
然后,在python中
import os
print os.environ["test1"]
Run Code Online (Sandbox Code Playgroud)
还有另一种subprocess
不依赖于设置环境的使用方式。不过,多一点代码。
对于如下所示的 shell 脚本:
#!/bin/sh
myvar="here is my variable in the shell script"
function print_myvar() {
echo $myvar
}
Run Code Online (Sandbox Code Playgroud)
您可以检索变量的值,甚至可以在 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')
Run Code Online (Sandbox Code Playgroud)
请注意,两者shell=True
都应设置以便按CMD
原样处理要处理的 shell 命令,并设置executable='bin/bash'
为使用进程替换,默认情况下不支持/bin/sh
。
归档时间: |
|
查看次数: |
49248 次 |
最近记录: |