使用PyYaml解析yaml文件?

2024-06-26 05:55:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个.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

Tags: httpsgitgithubcomurlsourcereleaseversion
2条回答

我更新了获取URL()以返回请求的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']

yaml.load(stream)将读取整个文件并将其存储为python数据结构。然后可以使用列表或字典操作来检索URL。基本上,您可以分别通过索引或键进行访问

相关问题 更多 >