如何使用python脚本替换要解析的yaml文件中的环境变量值 [英] How to replace environment variable value in yaml file to be parsed using python script
问题描述
我需要在需要用脚本解析的 yaml 文件中使用环境变量PATH".
I need to use environment variable "PATH" in yaml file which needs to be parsed with a script.
这是我在终端上设置的环境变量:
This is the environment variable I have set on my terminal:
$ echo $PATH
/Users/abc/Downloads/tbwork
这是我的sample.yml:
This is my sample.yml:
---
Top: ${PATH}/my.txt
Vars:
- a
- b
当我用我的脚本解析这个 yaml 文件时,我没有看到 PATH
变量的实际值.
When I parse this yaml file with my script, I don't see PATH
variables actual value.
这是我的脚本:
import yaml
import os
import sys
stream = open("sample.yml", "r")
docs = yaml.load_all(stream)
for doc in docs:
for k,v in doc.items():
print k, "->", v
print "\n",
输出:
Top -> ${PATH}/my.txt
Vars -> ['a', 'b']
预期输出为:
Top -> /Users/abc/Downloads/tbwork/my.txt
Vars -> ['a', 'b']
如果我做错了,有人能帮我找出正确的方法吗?
Can someone help me figuring out the correct way to do it if I am doing it wrong way?
推荐答案
PY-yaml 库默认不解析环境变量.您需要定义一个隐式解析器,它将找到定义环境变量的正则表达式并执行一个函数来解析它.
PY-yaml library doesn't resolve environment variables by default. You need to define an implicit resolver that will find the regex that defines an environment variable and execute a function to resolve it.
您可以通过yaml.add_implicit_resolver
和yaml.add_constructor
来实现.在下面的代码中,您正在定义一个解析器,该解析器将匹配 YAML 值中的 ${ env variable } 并调用函数 path_constructor 以查找环境变量.
You can do it through yaml.add_implicit_resolver
and yaml.add_constructor
. In the code below, you are defining a resolver that will match on ${ env variable } in the YAML value and calling the function path_constructor to look up the environment variable.
import yaml
import re
import os
path_matcher = re.compile(r'\$\{([^}^{]+)\}')
def path_constructor(loader, node):
''' Extract the matched value, expand env variable, and replace the match '''
value = node.value
match = path_matcher.match(value)
env_var = match.group()[2:-1]
return os.environ.get(env_var) + value[match.end():]
yaml.add_implicit_resolver('!path', path_matcher)
yaml.add_constructor('!path', path_constructor)
data = """
env: ${VAR}/file.txt
other: file.txt
"""
if __name__ == '__main__':
p = yaml.load(data, Loader=yaml.FullLoader)
print(os.environ.get('VAR')) ## /home/abc
print(p['env']) ## /home/abc/file.txt
警告:如果您不是指定 env 变量(或任何其他不受信任的输入)的人,请不要运行此程序,因为截至 2020 年 7 月,FullLoader 存在远程代码执行漏洞.
Warning: Do not run this if you are not the one specifying the env variables (or any other untrusted input) as there are remote code execution vulnerabilities with FullLoader as of July 2020.
这篇关于如何使用python脚本替换要解析的yaml文件中的环境变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!