我正在尝试仅打印出 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'}
关于python - Boto3 - 打印 AWS 实例平均 CPU 利用率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50044759/