【问题标题】:How to call and iterate values from a yaml file parsed using python?如何从使用 python 解析的 yaml 文件中调用和迭代值?
【发布时间】:2018-10-07 17:08:52
【问题描述】:
  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") 打印(配置)

我的问题: 1. 我无法返回值,并且在函数外部调用的打印语句中出现“NameError: name 'config' is not defined”。

  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']))
    

感谢您的帮助。

【问题讨论】:

    标签: python iterator duplicates nameerror


    【解决方案1】:
    1. 您会收到NameError 异常,因为您没有返回任何值。您必须从函数中返回 config

    例如:

    def read_yaml(...):
        # code
    
         return config
    

    然后,通过调用read_yaml,您将返回您的配置。

    查看Python documentation 和教程。

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

    例如:

    x = {'lol': 1, 'kek': 2}
    
    for name, value in x.items():
        print(name, value)
    

    【讨论】:

    • 谢谢。假设我有 x,y,z,a,b,c..etc 那么你知道如何处理这种情况吗?
    猜你喜欢
    • 1970-01-01
    • 2020-12-09
    • 2012-07-20
    • 2010-12-18
    • 1970-01-01
    • 2020-10-14
    • 2020-07-18
    • 1970-01-01
    • 2019-06-23
    相关资源
    最近更新 更多