如何使用 PyYAML 从 Bash 查找 YAML 值

我正在测试在 RHEL7 环境中使用 PyYAML v3.12 来解析中等复杂的 YAML 配置文件内容的可行性,方法是向其提供密钥并获取密钥对值。该查询看起来像这样python my_yaml_search.py key_to_search并打印回value,例如:


所需的 bash 命令:python search_yaml.py $servername


所需的响应(仅值,而不是键值):myServer14


到目前为止,我已经创建了以下 .py:


import sys

import yaml

key = sys.argv[1]


with open("config.yml") as f:

    try:

        data = yaml.safe_load(f)

        for k, v in data.items():

            if data[k].has_key(key):

                print data[k][v]

    

    except yaml.YAMLError as exc:

        print "Error: key not found in YAML"

配置.yml:


---

server:

    servername: myServer14

    filename: testfile.zip

    location: http://test-location/1.com

    repo:

        server_name_fqdn: server.name.fqdn.com

        port: 1234


到目前为止,运行python search_yaml.py $servername会产生list index out of range; python search_yaml.py servername什么也不产生。我是 Python/PyYAML 的新手,所以我认为我可能错误地向程序传递了一个变量,并且 sys 可能不是我需要的 Python 库,但是我在如何正确执行此操作方面遇到了障碍 -任何输入都会挽救我的理智。


喵喔喔
浏览 97回答 1
1回答

qq_花开花谢_0

如果您知道要遍历的所有键,则可以执行以下操作:import sysimport yamlkey = sys.argv[1]with open("config.yml") as f:&nbsp; &nbsp; data = yaml.safe_load(f)&nbsp; &nbsp; n = key.count('.')&nbsp; &nbsp; parts = key.split('.')&nbsp; &nbsp; res = None&nbsp; &nbsp; i = 0&nbsp; &nbsp; while i <= n:&nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if not res:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res = data[parts[i]]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res = res[parts[i]]&nbsp; &nbsp; &nbsp; &nbsp; except (yaml.YAMLError, KeyError) as exc:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print ("Error: key not found in YAML")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res = None&nbsp; &nbsp; &nbsp; &nbsp; i = i + 1&nbsp; &nbsp; if res:&nbsp; &nbsp; &nbsp; &nbsp; print(res)测试~# python search_yaml.py server.repo.port~# 1234~# python search_yaml.py server.servername~# myServer14这可能有错误,我编写代码只是为了看看是否可以在没有第三方工具的情况下轻松完成。适用于 YAML 的 CLI 应用程序浏览本次作品的您可能还对程序感兴趣yq。实际上有两个同名的程序,一个是用 Go 实现的,另一个是基于 Python 的(可能比上面的代码更复杂):-)基于Go的yq. yq您可以从 GitHub 版本安装提供的静态编译的二进制文件,也可以yum使用商业GetPageSpeed 存储库进行安装,以便以后轻松更新:sudo yum -y install https://extras.getpagespeed.com/release-latest.rpmsudo yum -y install yq然后你可以简单地:~# yq read config.yml server.servername~# myServer14
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python