【问题标题】:Mapping yaml file contents to a list in python将yaml文件内容映射到python中的列表
【发布时间】:2019-03-20 01:54:22
【问题描述】:

我有一个结构如下的 yaml 文件:

这是 test.yaml

    server:
      - host: ubuntu
        ip: 10.20.30.40
        path: /var/log/syslog
      - host: ubuntu
        ip: 10.20.3.50
        path: /var/log/syslog

当我调用我的 python 脚本时,我会加载 yaml 文件并解析内容。我无法迭代所有内容:

如何创建以下格式的列表:

    import yaml



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

    d = read_yaml("config.yaml")


    print('{host}@{ip}:{path}'.format(*d['server']))

我想要 yaml 文件中不同服务器的 host@ip:path 输出。但是上面的命令不起作用并产生错误:TypeError: format() argument after ** must be a mapping, not list 要么 KeyError:主机

请帮忙。

【问题讨论】:

    标签: python list mapping


    【解决方案1】:

    您解压缩列表 (d['server']) 作为 format 的参数。但在这种情况下,格式需要命名关键字参数(kwargs)。

    由于您应该只希望在每个这样的 print 呼叫中打印 1 个项目,请尝试:

    for item in d['server']:
        print('{host}@{ip}:{path}'.format(**item))
    

    【讨论】:

      猜你喜欢
      • 2018-11-23
      • 2016-07-13
      • 2018-04-03
      • 2015-12-12
      • 1970-01-01
      • 2019-07-25
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多