简体   繁体   English

使用python解析Yaml文件时出现问题

[英]Having a problem to parse Yaml file with python

I have the below section in YML file and I'm trying to read the IP address and hostname of the servers in order to verify that I don't have duplication (can see each IP once and each hostname)我在 YML 文件中有以下部分,我正在尝试读取服务器的 IP 地址和主机名,以验证我没有重复(可以看到每个 IP 一次和每个主机名)

I'm failing at the first stage while trying to ready the IP address.我在第一阶段尝试准备 IP 地址时失败了。 WIll be happy to get help with both reading and verify there is no duplication很乐意在阅读和验证没有重复方面获得帮助

Thank you谢谢

import yaml


with open(r'.\environment.yml') as file:
    environment = yaml.load(file, Loader=yaml.FullLoader)
print(environment ['server_details']['ip'])
YML File YML文件
server_details: - {ip: "{{ yum_repository.ip }}" , hostname: "{{ yum_repository.hostname }}"} - {ip: "{{ cloudera_managment_server.ip }}" , hostname: "{{ cloudera_managment_server.hostname }}"} - {ip: "{{ postgres_server.ip }}" , hostname: "{{ postgres_server.hostname }}"} - {ip: 10.201.51.30 , hostname: master1} - {ip: 10.201.51.31 , hostname: master2} - {ip: 10.201.51.32 , hostname: master3} - {ip: 10.201.51.36 , hostname: worker1} - {ip: 10.201.51.37 , hostname: worker2} - {ip: 10.201.51.38 , hostname: worker3} - {ip: 10.201.51.39 , hostname: kafka1} - {ip: 10.201.51.40 , hostname: kafka2} - {ip: 10.201.51.41 , hostname: kafka3} - {ip: 10.201.51.44 , hostname: gw1}

As @AdamSmith mentioned, you should traverse(or index) list first.正如@AdamSmith 提到的,您应该先遍历(或索引)列表。

import yaml


with open(r'.\environment.yml') as file:
    environment = yaml.load(file, Loader=yaml.FullLoader)
for server_detail in environment['server_details']:
    print(server_detail['ip'])

You can make it list, too你也可以把它列出来

ip_list = [server_detail['ip'] for server_detail in environment['server_details']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM