bash 从 shell 脚本加载环境变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31117531/
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
Load environment variables from a shell script
提问by lafferc
I have a file with some environment variables that I want to use in a python script
我有一个文件,其中包含一些我想在 python 脚本中使用的环境变量
The following works form the command line
以下工作形成命令行
$ source myFile.sh
$ python ./myScript.py
and from inside the python script I can access the variables like
从 python 脚本内部,我可以访问变量,如
import os
os.getenv('myvariable')
How can I source the shell script, then access the variables, from with the python script?
如何获取 shell 脚本,然后使用 python 脚本访问变量?
回答by Jason Hu
If you are saying backward environment propagation, sorry, you can't. It's a security issue. However, directly source environment from python is definitely valid. But it's more or less a manual process.
如果你说的是向后环境传播,对不起,你不能。这是一个安全问题。但是,直接从 python 源环境是绝对有效的。但这或多或少是一个手动过程。
import subprocess as sp
SOURCE = 'your_file_path'
proc = sp.Popen(['bash', '-c', 'source {} && env'.format(SOURCE)], stdout=sp.PIPE)
source_env = {tup[0].strip(): tup[1].strip() for tup in map(lambda s: s.strip().split('=', 1), proc.stdout)}
Then you have everything you need in source_env
.
然后你就拥有了你需要的一切source_env
。
If you need to write it back to your local environment (which is not recommended, since source_env
keeps you clean):
如果您需要将其写回本地环境(不推荐这样做,因为source_env
可以保持清洁):
import os
for k, v in source_env.items():
os.environ[k] = v
Another tiny attention needs to be paid here, is since I called bash
here, you should expect the rules are applied here too. So if you want your variable to be seen, you will need to export them.
这里需要注意的另一个小问题是,既然我bash
在这里打电话,你应该期望这里也适用规则。因此,如果您希望看到您的变量,则需要导出它们。
export VAR1='see me'
VAR2='but not me'
回答by Mike DuPont
You can notload environmental variables in general from a bash or shell script, it is a different language. You will have to use bash to evaluate the file and then somehow print out the variables and then read them. see Forcing bash to expand variables in a string loaded from a file
通常您不能从 bash 或 shell 脚本加载环境变量,它是一种不同的语言。您将不得不使用 bash 来评估文件,然后以某种方式打印出变量,然后读取它们。请参阅强制 bash 扩展从文件加载的字符串中的变量