繁体   English   中英

Boto3 - 打印 AWS 实例平均 CPU 利用率

[英]Boto3 - Print AWS Instance Average CPU Utilization

我试图打印出 AWS 实例的平均 CPU 使用率。 此代码将打印出“响应”,但末尾的 for 循环不会打印平均利用率。 有人可以帮忙吗? 先感谢您!

    import boto3
    import sys
    from datetime import datetime, timedelta
        client = boto3.client('cloudwatch')
        response = client.get_metric_statistics(
            Namespace='AWS/EC2',
            MetricName='CPUUtilization',
            Dimensions=[
                {
                'Name': 'InstanceId',
                'Value': 'i-1234abcd'
                },
            ],
            StartTime=datetime(2018, 4, 23) - timedelta(seconds=600),
            EndTime=datetime(2018, 4, 24),
            Period=86400,
            Statistics=[
                'Average',
            ],
            Unit='Percent'
        )
    for cpu in response:
        if cpu['Key'] == 'Average':
            k = cpu['Value']
    print(k)

这是我收到的错误消息:

    Traceback (most recent call last):
      File "C:\bin\TestCW-CPU.py", line 25, in <module>
        if cpu['Key'] == 'Average':
    TypeError: string indices must be integers
for cpu in response['Datapoints']:
  if 'Average' in cpu:
    print(cpu['Average'])

2.25348611111
2.26613194444

如果您打印cpu的值,您就会明白为什么会这样:

print(response)

for cpu in response['Datapoints']:
  print(cpu)

{u'Timestamp': datetime.datetime(2018, 4, 23, 23, 50, tzinfo=tzlocal()), u'Average': 2.2534861111111106, u'Unit': 'Percent'}
{u'Timestamp': datetime.datetime(2018, 4, 22, 23, 50, tzinfo=tzlocal()), u'Average': 2.266131944444444, u'Unit': 'Percent'}

这将输出平均 CPU:

    for k, v in response.items():
        if k == 'Datapoints':
        for y in v:
            print(y['Average'])

您只需要从响应中过滤“数据点”,然后打印平均值:

for cpu in response['Datapoints']:
        print(cpu['Average'])

此外,如果您想使用列表来表示所有值的平均值:

# faster code
average = [cpu['Average'] for cpu in response['Datapoints']]

上面的平均值列表可用于平均值:

# if list is not empty
if average:
    print('Mean : ',sum(average)/len(average))

暂无
暂无

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

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