簡體   English   中英

如何從使用python解析的yaml文件中調用和迭代值?

[英]How to call and iterate values from a yaml file parsed using python?

  1. 我有一個yaml文件,如下所示:

     server1: host: os1 ip: ##.###.#.## path: /var/log/syslog file: syslog identityfile: /identityfile/keypair.pub server2: host: os2 ip: ##.###.#.## path: /var/log/syslog file: syslog.1 identityfile: /identityfile/id_rsa.pub 

我有一段代碼來解析yaml和讀取條目。

從配置yaml文件中讀取數據

    def read_yaml(file):
        with open(file, "r") as stream:
    try:
        config = yaml.load(stream)
        print(config)
    except yaml.YAMLError as exc:
        print(exc)
        print("\n")
return config

read_yaml(“ config_file”)print(config)

我的問題:1.我無法返回值,並且在函數外部調用的打印語句上收到“ NameError:未定義名稱'config'”。

  1. 如何通過僅傳遞參數來迭代和讀取yaml文件中的值? 例如:print('{host} @ {ip}:{path}'。format(** config ['os1']))),但沒有'os1',因為yaml文件可能有100個條目

  2. 我通過使用集合確保沒有重復項,但想使用循環並將字符串格式化命令中的值存儲到變量中,而不使用'os1'或'os2'或'os#'。

     def iterate_yaml(): remotesys = set() for key,val in config.items(): print("{} = {}".format(key,val)) #check to ensure duplicates are removed by storing it in a set remotesys.add('{host}@{ip}:{path}'.format(**config['os1'])) remotesys.add('{host}@{ip}:{path}'.format(**config['os2'])) remotesys.add('{host}@{ip}:{path}'.format(**config['os3'])) 

謝謝您的幫助。

  1. 您會收到NameError異常,因為您沒有返回任何值。 您必須從函數返回config

例如:

def read_yaml(...):
    # code

     return config

然后,通過調用read_yaml ,將返回您的配置。

查看Python文檔和教程。

2-3。 您可以使用dict.items方法執行for循環。

例如:

x = {'lol': 1, 'kek': 2}

for name, value in x.items():
    print(name, value)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM