首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将YAML文件包含在另一个文件中?

如何将YAML文件包含在另一个文件中?
EN

Stack Overflow用户
提问于 2009-02-09 14:14:05
回答 9查看 286.2K关注 0票数 376

因此,我有两个YAML文件,"A“和" B”,我希望将A的内容插入到B中,要么像数组一样拼接到现有的数据结构中,要么像某个散列键的值一样作为元素的子元素。

这到底有没有可能?多么?如果不是,有没有关于规范参考的建议?

EN

回答 9

Stack Overflow用户

回答已采纳

发布于 2013-03-16 00:39:30

不,YAML不包含任何类型的"import“或" include”语句。

票数 397
EN

Stack Overflow用户

发布于 2012-01-24 02:45:23

据我所知,在YAML中不直接支持Include,你必须自己提供一种机制,但这通常很容易做到。

我在我的python应用程序中使用了YAML作为配置语言,在这种情况下,通常会定义如下约定:

代码语言:javascript
复制
>>> main.yml <<<
includes: [ wibble.yml, wobble.yml]

然后在我的(python)代码中,我这样做:

代码语言:javascript
复制
import yaml
cfg = yaml.load(open("main.yml"))
for inc in cfg.get("includes", []):
   cfg.update(yaml.load(open(inc)))

唯一的缺点是includes中的变量将始终覆盖main中的变量,并且无法通过更改"includes:语句“在main.yml文件中的出现位置来更改优先顺序。

从另一个角度来看,YAML并不支持includes,因为它的设计并不像基于文件的标记那样专一。如果您在对AJAX请求的响应中获得了include,那么include意味着什么?

票数 17
EN

Stack Overflow用户

发布于 2012-09-04 01:58:44

根据@Josh_Bode的回答,下面是我自己的PyYAML解决方案,它的优点是它是yaml.Loader的一个自包含子类。它不依赖于任何模块级全局变量,也不依赖于修改yaml模块的全局状态。

代码语言:javascript
复制
import yaml, os

class IncludeLoader(yaml.Loader):                                                 
    """                                                                           
    yaml.Loader subclass handles "!include path/to/foo.yml" directives in config  
    files.  When constructed with a file object, the root path for includes       
    defaults to the directory containing the file, otherwise to the current       
    working directory. In either case, the root path can be overridden by the     
    `root` keyword argument.                                                      

    When an included file F contain its own !include directive, the path is       
    relative to F's location.                                                     

    Example:                                                                      
        YAML file /home/frodo/one-ring.yml:                                       
            ---                                                                   
            Name: The One Ring                                                    
            Specials:                                                             
                - resize-to-wearer                                                
            Effects: 
                - !include path/to/invisibility.yml                            

        YAML file /home/frodo/path/to/invisibility.yml:                           
            ---                                                                   
            Name: invisibility                                                    
            Message: Suddenly you disappear!                                      

        Loading:                                                                  
            data = IncludeLoader(open('/home/frodo/one-ring.yml', 'r')).get_data()

        Result:                                                                   
            {'Effects': [{'Message': 'Suddenly you disappear!', 'Name':            
                'invisibility'}], 'Name': 'The One Ring', 'Specials':              
                ['resize-to-wearer']}                                             
    """                                                                           
    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                                                      
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/528281

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档