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

jmo*_*ead 5 python amazon-ec2 amazon-web-services boto3

我正在尝试仅打印出 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)
Run Code Online (Sandbox Code Playgroud)

这是我收到的错误消息:

    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
Run Code Online (Sandbox Code Playgroud)

hel*_*loV 5

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

2.25348611111
2.26613194444
Run Code Online (Sandbox Code Playgroud)

如果您打印以下值,您就会明白为什么会这样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'}
Run Code Online (Sandbox Code Playgroud)


jmo*_*ead 5

这将输出平均 CPU:

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