将Bash变量读入Python脚本 [英] Read Bash variables into a Python script
问题描述
我正在运行一个bash脚本(test.sh),它会加载环境变量(来自env.sh)。那很好,但是我试图看到python可以加载bash脚本中已经存在的变量。
是的,我知道将我需要的特定变量作为参数传递可能会更容易,但是我很好奇是否有可能获得bash变量。 / p>
test.sh
#!/ bin / bash
source env.sh
echo $ test1
python pythontest.py
env.sh
#!/ bin / bash
test1 = hello
pythontest.py
?
print test1(这就是我想要的)
您需要在bash中导出变量,否则它们将是bash的本地变量:
export test1
然后,以python
import os
print os.environ [ test1]
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.
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.
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)
You need to export the variables in bash, or they will be local to bash:
export test1
Then, in python
import os
print os.environ["test1"]
这篇关于将Bash变量读入Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!