How can I parse a YAML file in Python

后端 未结 8 1097
醉话见心
醉话见心 2020-11-22 14:54

How can I parse a YAML file in Python?

相关标签:
8条回答
  • 2020-11-22 15:34

    The easiest and purest method without relying on C headers is PyYaml (documentation), which can be installed via pip install pyyaml:

    #!/usr/bin/env python
    
    import yaml
    
    with open("example.yaml", 'r') as stream:
        try:
            print(yaml.safe_load(stream))
        except yaml.YAMLError as exc:
            print(exc)
    

    And that's it. A plain yaml.load() function also exists, but yaml.safe_load() should always be preferred unless you explicitly need the arbitrary object serialization/deserialization provided in order to avoid introducing the possibility for arbitrary code execution.

    Note the PyYaml project supports versions up through the YAML 1.1 specification. If YAML 1.2 specification support is needed, see ruamel.yaml as noted in this answer.

    0 讨论(0)
  • 2020-11-22 15:35
    #!/usr/bin/env python
    
    import sys
    import yaml
    
    def main(argv):
    
        with open(argv[0]) as stream:
            try:
                #print(yaml.load(stream))
                return 0
            except yaml.YAMLError as exc:
                print(exc)
                return 1
    
    if __name__ == "__main__":
        sys.exit(main(sys.argv[1:]))
    
    0 讨论(0)
提交回复
热议问题