How can I do string concatenation, or string replacement in YAML?

后端 未结 7 2272
深忆病人
深忆病人 2020-12-01 08:38

I have this:

user_dir: /home/user
user_pics: /home/user/pics

How could I use the user_dir for user_pics? If I have to specify

7条回答
  •  孤城傲影
    2020-12-01 09:28

    As of August 2019:

    To make Chris' solution work, you actually need to add Loader=yaml.Loader to yaml.load(). Eventually, the code would look like this:

    import yaml
    
    ## define custom tag handler
    def join(loader, node):
        seq = loader.construct_sequence(node)
        return ''.join([str(i) for i in seq])
    
    ## register the tag handler
    yaml.add_constructor('!join', join)
    
    ## using your sample data
    yaml.load("""
    user_dir: &DIR /home/user
    user_pics: !join [*DIR, /pics]
    """, Loader=yaml.Loader)
    

    See this GitHub issue for further discussion.

提交回复
热议问题