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"
這個庫在用於讀取公共配置時非常有用,對於不同的配置文件將其中的公共部分提出生成一個新的配置文件,其他的配置文件調用公共配置,便於后續對公共配置的修改。