将Bash变量读入Python脚本 [英] Read Bash variables into a Python script

查看:69
本文介绍了将Bash变量读入Python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆