我编写了从API获取数据的代码。我能够解析API中的JSON数据。我只通过API过滤出正在运行的实例并提取其数据。输出是一个JSON响应。
我想:
instances.
corecount和ThreadsPerCore值,vcpus相乘的corecountx ThreadsPerCore = vcpus相加。H 212G 213我如何编写这样做的代码?
我读了一些教程,所以我知道我需要使用[]来访问嵌套列表和字典的元素;我尝试使用它来检索单个数据集(例如-1)的值,但是在我的例子中,我无法确切地知道它是如何工作的,我可能有'n‘个数据集(实例1,2,3,……)需要获得具有特定值的数据。因此,我在这里实现了for loop,当我不得不执行算术操作时,工作也变得复杂起来。
在本例中,JSON输出结构包含3组数据(针对3个正在运行的实例),但根据场景可能有所不同:
{
"Reservations": [
{
"Groups": [],
"Instances": [
{
"AmiLaunchIndex": 0,
"ImageId": "ami-123",
"InstanceId": "INSTANCE-1",
"InstanceType": "t2.micro",
"KeyName": "MyKeyPair",
"State": {
"Code": 16,
"Name": "running"
},
"StateTransitionReason": "",
"CpuOptions": {
"CoreCount": 4,
"ThreadsPerCore": 2
},
],
"OwnerId": "123456789012"
"ReservationId": "r-02a3f596d91211712",
},
{
"Groups": [],
"Instances": [
{
"AmiLaunchIndex": 0,
"ImageId": "ami-123",
"InstanceId": "INSATNCE-2",
"InstanceType": "t2.micro",
"KeyName": "MyKeyPair",
"State": {
"Code": 16,
"Name": "running"
},
"StateTransitionReason": "",
"CpuOptions": {
"CoreCount": 8,
"ThreadsPerCore": 2
},
],
"OwnerId": "123456789012"
"ReservationId": "r-02a3f596d91211712",
},
{
"Groups": [],
"Instances": [
{
"AmiLaunchIndex": 0,
"ImageId": "ami-123",
"InstanceId": "INSTANCE-3",
"InstanceType": "t2.micro",
"KeyName": "MyKeyPair",
"State": {
"Code": 16,
"Name": "running"
},
"StateTransitionReason": "",
"CpuOptions": {
"CoreCount": 4,
"ThreadsPerCore": 2
},
],
"OwnerId": "123456789012"
"ReservationId": "r-02a3f596d91211712",
}
]
}检索CpuOptions:CoreCount和ThreadsPerCore值的代码如下:
from shell import run_command_str
import json
cmd = "aws ec2 describe-instances --output json --filters Name=instance-state-name,Values=running"
output = run_command_str(command=cmd, shell_command=True)
status = json.loads(output)
corecount = {}
for reservation in status1["Reservations"]:
for instance in reservation["Instances"]:
corecount[instance["InstanceId"]] = instance["CpuOptions"]["CoreCount"]
print(corecount)
threadspercore = {}
for reservation in status1["Reservations"]:
for instance in reservation["Instances"]:
threadspercore[instance["InstanceId"]] = instance["CpuOptions"]["ThreadsPerCore"]
print(threadspercore)此代码的输出:
{'INSTANCE-1': 4, 'INSTANCE-2': 8, 'INSTANCE-3': 4} ###corecount values
{'INSTANCE-1': 2, 'INSTANCE-2': 2, 'INSTANCE-3': 2} ###Threadpercore values发布于 2022-08-11 17:53:41
如果我正确地理解了你,你想要计算vcpus和来自corecount和threadspercore的所有vcpus之和。
corecount = {"INSTANCE-1": 4, "INSTANCE-2": 8, "INSTANCE-3": 4}
threadspercore = {"INSTANCE-1": 2, "INSTANCE-2": 2, "INSTANCE-3": 2}
vcpus = {k: corecount[k] * threadspercore[k] for k in corecount}
sum_vcpus = sum(vcpus.values())
print(corecount)
print(threadspercore)
print(vcpus)
print(sum_vcpus)指纹:
{'INSTANCE-1': 4, 'INSTANCE-2': 8, 'INSTANCE-3': 4}
{'INSTANCE-1': 2, 'INSTANCE-2': 2, 'INSTANCE-3': 2}
{'INSTANCE-1': 8, 'INSTANCE-2': 16, 'INSTANCE-3': 8}
32https://stackoverflow.com/questions/73323924
复制相似问题