繁体   English   中英

Python:从文件中解析YAML数据

[英]Python: YAML data parsing from a file

我有以下YAML数据

- gms:
  - localhost1:
      address: 192.168.56.101
      username: root
      password: xxxxxx
      command: "uptime"
      hostname: mydev_machine

我正在尝试使用以下逻辑在python中提取addresspasswordcommandhostname

import yaml

with open("host_data.yaml",'r') as stream :
  data_loaded = yaml.load(stream)

for element in data_loaded:
  address=element['gms']['localhost1']['address']
  username=element['gms']['localhost1']['username']
  password=element['gms']['localhost1']['password']
  hostname=element['gms']['localhost1']['hostname']

如果我看一下print(data_loaded)输出

[{'gms': [{'localhost1': {'address': '192.168.56.101', 'username': 'root', 'password': 'xxxxxx', 'command': 'uptime', 'hostname': 'mydev_machine'}}]}]

但我得到错误

Traceback (most recent call last):
  File "Python_Programs/log_finder.py", line 12, in <module>
    address=element['gms']['localhost1']['address']
TypeError: list indices must be integers or slices, not str

element.get('gms')element['gms']产生一个列表。 您需要迭代列表。

for element in data_loaded:
    for item in element.get('gms'):
        print(item.get('localhost1').get('address'))

您还可以像这样访问list的元素:

element['gms'][0]['localhost1']['address']

暂无
暂无

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

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