python 语言 yaml文件嵌套另一个yaml

python的第三方库非常的强大,感谢所有贡献第三方库的大大们。

在这里记录一下最近使用到非常好用的第三方库:pyyaml-include

安装:

pip install pyyaml-include

使用:

假设有这样的目录结构

├── base
  ├── base.yml
└── sub
  ├── sub1.yml 
  └── sub2.yml
└── case
  ├──test.py

在base.yml文件中引用sub1.yml和sub2.yml

修改test.py中的代码:

import yaml, os
from yamlinclude import YamlIncludeConstructor
fpath = os.path.dirname(os.path.dirname(__file__))
Path = lambda p:os.path.join(fpath,p)
YamlIncludeConstructor.add_to_loader_class(loader_class=yaml.FullLoader)
def test(path):
    p = Path(fpath, path)
    with open(p) as f:
        data = yaml.load(f, Loader=yaml.FullLoader)
    return data 

if __name__ == '__main__':
    path = 'base/base.yml'
    t = test(path)
    print(t)

sub1.yml文件中的内容

name1: "hello"

sub2.yml文件中的内容

name2: "world"

base.yml文件的内容(映射到sub1.yml,sub2.yml)

file1: !include "sub/sub1.yml"

fle2: !include "sub/sub2.yml"

执行test.py输出的t

file1:
    name1: "hello"
file2:
    name2: "world"

这个库在用于读取公共配置时非常有用,对于不同的配置文件将其中的公共部分提出生成一个新的配置文件,其他的配置文件调用公共配置,便于后续对公共配置的修改。

 
原文地址:https://www.cnblogs.com/wx2017/p/12696416.html