python - 使用 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.git
和https://github.com/ros2/cartographer.git
URL。
我在下面写了一些代码,但本质上,我想将上面列出的 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
解决方案
我更新了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']
推荐阅读
- css - 单击导航菜单时如何激活状态?
- mysql - 在 where 子句中使用参数的超集 sql 查询编辑器
- python - 当我绘制超过 2 个值时,为什么 Timer 会破坏我的数据?
- sql - 在 sql server 2016 中创建内存表时的桶计数帮助
- azure - 按每个事件组的时间戳显示第一个条目
- python - 将字符串 numpy.ndarray 转换为浮点数 numpy.ndarray
- django - 更改数据库后重新启动 Django 服务器
- c# - 如何实现 Android ISO 并将其加载到 C# WinForm 应用程序中?
- marklogic - 路径范围索引方面搜索在 Marklogic 9 中不起作用
- java - Mockito 让 mock 从现有的 mock 继承存根