Round-trip parsing of data structure format (YAML or whatnot) preserving comments, for writing configuration

后端 未结 3 977
迷失自我
迷失自我 2021-02-13 21:16

I have been using YAML as configuration file format in several applications, and all went well except one thing: when my program needs to write/modify a config variable in a YAM

3条回答
  •  感动是毒
    2021-02-13 22:01

    If you are using block structured YAML and Python is acceptable, you can use the Python package¹ ruamel.yaml which is a derivative of PyYAML and supports round trip preservation of comments:

    import sys
    import ruamel.yaml
    
    inp = """\
    # example
    name:
      # details
      family: Smith   # very common
      given: Alice    # one of the siblings
    """
    
    yaml = ruamel.yaml.YAML()
    
    code = yaml.load(inp)
    code['name']['given'] = 'Bob'
    
    yaml.dump(code, sys.stdout)
    

    with result:

    # example
    name:
      # details
      family: Smith   # very common
      given: Bob      # one of the siblings
    

    Note that the end-of-line comments are still aligned.

    Instead of normal list and dict objects the code consists of wrapped versions² on which the comments attached.

    ¹ Install with pip install ruamel.yaml. Works on Python 2.6/2.7/3.3+. Disclaimer: I am the author of that package.
    ² ordereddict is used in case of a mapping, to preserve ordering

提交回复
热议问题