|--------a
|----a.yaml
|----b.yaml
|--------c
|----c.yaml
|--------yaml_include.py
import yaml import os.path class Loader(yaml.Loader): def __init__(self, stream): self._root = os.path.split(stream.name)[0] super(Loader, self).__init__(stream) def include(self, node): filename = os.path.join(self._root, self.construct_scalar(node)) with open(filename, 'r') as fr: return yaml.load(fr, Loader) Loader.add_constructor('!include', Loader.include) def load_yaml(file_name): """Load YAML file to be dict""" if os.path.exists(file_name): with open(file_name, 'r', encoding="utf-8") as fr: dict_obj = yaml.load(fr, Loader=Loader) return dict_obj else: raise FileNotFoundError('NOT Found YAML file %s' % file_name) if __name__ == '__main__': yaml_dict = load_yaml("a/a.yaml") print(yaml_dict)
a.yaml
name: demo hobby: !include ./b.yaml # 引用当前目录下yaml文件 skill: !include ../c/c.yaml # 引用非当前目录下的yaml文件
b.yaml
- basketball - Table-Tennis - swim
c.yaml
- python - java - shell - linux
打印结果:
{ "hobby": ["basketball", "Table-Tennis", "swim"], "name": "demo", "skill": ["python", "java", "shell", "linux"] }
a.yaml
name: demo maodiao1: &maodian1 # &符号标记锚点1 a: 1 b: 2 maodiao2: &maodian2 # &符号标记锚点2 aa: 11 bb: 22 haha: <<: *maodian1 # 方式一:使用 <<: * 符号引用 heihei: *maodian2 # 方式二:直接使用*号引用
打印结果:
{ "name": "demo", "maodiao1": {"a": 1, "b": 2}, "maodiao2": {"aa": 11, "bb": 22}, "haha": {"a": 1,"b": 2}, "heihei": {"aa": 11,"bb": 22} }
a.yaml
name: demo maodian1: &maodian1 # &符号标记锚点1 hobby: !include ./b.yaml # 引用当前目录下yaml文件 skill: !include ../c/c.yaml # 引用非当前目录下的yaml文件 maodiao2: &maodian2 # &符号标记锚点2 aa: 11 bb: 22 haha: <<: *maodian1 # 方式一:使用 <<: * 符号引用 heihei: *maodian2 # 方式二:直接使用*号引用
b.yaml
- basketball - Table-Tennis - swim
c.yaml
- python - java - shell - linux
打印结果
{ "name": "demo", "maodian1": { "hobby": ["basketball", "Table-Tennis", "swim"], "skill": ["python", "java", "shell", "linux"] }, "maodiao2": {"aa": 11,"bb": 22}, "haha": { "hobby": ["basketball", "Table-Tennis", "swim"], "skill": ["python", "java", "shell", "linux"] }, "heihei": {"aa": 11,"bb": 22} }