yaml文件嵌套

python的pyyaml包中yaml嵌套还是基于在load中重载一个钩子类,对yaml的value进行解析处理。

具体的看以下代码:

#!/usr/bin/python
import os.path
import yaml

class IncludeLoader(yaml.Loader):
    def __init__(self, *args, **kwargs):
        super(IncludeLoader, self).__init__(*args, **kwargs)
        self.add_constructor('!include', self._include)
        if 'root' in kwargs:
            self.root = kwargs['root']
        elif isinstance(self.stream, file):
            self.root = os.path.dirname(self.stream.name)
        else:
            self.root = os.path.curdir

    def _include(self, loader, node):
        oldRoot = self.root
        filename = os.path.join(self.root, loader.construct_scalar(node))
        self.root = os.path.dirname(filename)
        data = yaml.load(open(filename, 'r'))
        self.root = oldRoot
        return data

class Config(object):
    def __init__(self, path):
        config_file = open(path, 'r')
        self.config_content = yaml.load(config_file, IncludeLoader)
        config_file.closed

    def getConfigContent(self):
        return self.config_content

通过pycharm跳入yaml.load,一直追到construct_object可以发现有如下部分:

yaml文件嵌套_第1张图片

可以看到是通过value前缀判定的!注意下面的a:后面要有一个空格。所以配置文件包含的格式如下:

cat total.yaml 
a: !include a.yaml
b: !include b.yaml

 

你可能感兴趣的:(python)