我以下面的YAML文件为例:
servers:
- type: staging
distribution_url: https://XXXXX
artifactory_url: https://YYYYY
假设我有distribution_url值,如何使用python命令获取类型值(0)?
答案 0 :(得分:2)
首先安装解析器,例如PyYAML。 Python标准库中没有YAML解析器。
import yaml
data = yaml.safe_load(your_yaml_string) # yaml from a string
# OR:
with open(your_yaml_fname) as f: # yaml from a file
data = yaml.safe_load(f)
然后:
>>> for server in data["servers"]:
... if server["distribution_url"] == "https://XXXXX":
... print(server["type"])
...
staging