首页 > 解决方案 > 使用 PyYaml 解析 yaml 文件?

问题描述

我有一个 .yaml 文件,里面有以下格式:

  ament_tools:
    release:
      tags:
        release: release/ardent/{package}/{version}
      url: https://github.com/ros2-gbp/ament_tools-release.git
      version: 0.4.0-0
    source:
      type: git
      url: https://github.com/ament/ament_tools.git
      version: ardent
    status: maintained
  cartographer:
    release:
      tags:
        release: release/ardent/{package}/{version}
      url: https://github.com/ros2-gbp/cartographer-release.git
      version: 2.0.0-1
    source:
      type: git
      url: https://github.com/ros2/cartographer.git
      version: ardent
    status: maintained

我想url检索source. 到目前为止,上面的示例,我想检索https://github.com/ament/ament_tools.githttps://github.com/ros2/cartographer.gitURL。

我在下面写了一些代码,但本质上,我想将上面列出的 URL 添加到urls我已初始化的列表中。我该如何具体解析source然后url

def get_urls(distribution):
    urls = list()
    tag1 = "source"
    tag2 = "url"
    
    # Open distribution.yaml file and collect urls in list
    for file in os.listdir("distribution/"):
        if file.startswith(distribution):
            dist_file = "distribution/" + file
            stream = open(dist_file, 'r')
            data = yaml.load(stream)
            

    print(urls)
    return urls

标签: pythonparsingsearchyamlpyyaml

解决方案


我更新了get_urls()以根据请求返回 URL 列表,否则没有。我希望我有所帮助。

def get_urls(distribution):
    urls = list()
    tag1 = "source"
    tag2 = "url"
    result_list = []
    # Open distribution.yaml file and collect urls in list
    try:
        for file in os.listdir("distribution/"):
            if file.startswith(distribution):
                dist_file = "distribution/" + file
                stream = open(dist_file, 'r')
                data = yaml.safe_load(stream)
    except:
        pass
    for elt in data:
        result_list.append(data[elt]['source']['url'])
    return result_list
    return None

输出:

['https://github.com/ament/ament_tools.git', 'https://github.com/ros2/cartographer.git']

推荐阅读