我正在编写一个导出监控数据的程序。
我有 python 代码,它发送 API 请求并获取字典形式的 json 响应。
响应如下所示:
[
{
"diskwrite": 667719532544,
"name": "test-hostname",
"maxmem": 536870912,
"diskread": 876677015576,
"mem": 496111616,
"id": "qemu/102",
"node": "node1",
"template": 0,
"cpu": 0.00947819269772254,
"vmid": 102,
"type": "qemu",
"maxcpu": 2,
"netout": 15081562546,
"maxdisk": 10737418240,
**"status": "running",**
"netin": 15852619497,
"disk": 0,
"uptime": 3273086
},
{
"maxcpu": 8,
"type": "qemu",
"vmid": 106,
"cpu": 0.500598230113925,
"template": 0,
"node": "node1",
"id": "qemu/106",
"mem": 10341007360,
"maxmem": 10737418240,
"diskread": 8586078094720,
"name": "some.other-hostname",
"diskwrite": 6052378838016,
"uptime": 1900411,
"disk": 0,
"netin": 4899018841106,
**"status": "stopping",**
"maxdisk": 107374182400,
"netout": 4788420573355
},
...
我想按原样循环遍历所有主机名及其项目(“diskwrite”、“mem”、“cpu”等),但仅当这些项目具有运行状态(“status”:“running”)。
ram_metric.set({'type': "total"}, ram[0])
cpu_metric.set({'type': 'average', 'interval': '5 minutes'}, cpu[0])
我还需要一个循环来生成这行代码,并为每个“name”项创建带有 host=name 的这一行:
ram_metric = Gauge("memory_usage_bytes", "Memory usage in bytes.",
{'host': host})
cpu_metric = Gauge("cpu_usage_percent", "CPU usage percent.",
{'host': host})
拜托,我不知道该怎么做。
最佳答案
也许我没有正确理解你的问题,因为我在理解你想要什么时遇到了一些困难。
如果您想获取所有主机名的列表,您可以执行以下操作。 您可以为此使用列表理解。像这样的东西:
running_hosts = [running_host['name'] for running_host in my_list_of_dicts if running_host['status'] == "running"]
关于Python 导出一些列表并将所有列表放入 for 循环中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44944256/