gpt4 book ai didi

python - 如何创建一个在每次调用时从先前值中减去当前值的函数

转载 作者:行者123 更新时间:2023-12-01 04:26:16 24 4
gpt4 key购买 nike

我正在查询一个工作原理如下的数据集:每次查询时,它都会生成不同的 Bytes_WrittenBytes_Read 值。我似乎无法完成的是从先前的值中减去当前的值并继续每秒执行此操作。

数据如下:

{
"Number of Devices": 2,
"Block Devices": {
"bdev0": {
"Backend_Device_Path": "/dev/disk/by-path/ip-192.168.26.1:3260-iscsi-iqn.2010-10.org.openstack:volume-d1c8e7c6-8c77-444c-9a93-8b56fa1e37f2-lun-010.0.0.142",
"Capacity": "2147483648",
"Guest_Device_Name": "vdb",
"IO_Operations": "97069",
"Bytes_Written": "34410496",
"Bytes_Read": "363172864"
},
"bdev1": {
"Backend_Device_Path": "/dev/disk/by-path/ip-192.168.26.1:3260-iscsi-iqn.2010-10.org.openstack:volume-b27110f9-41ba-4bc6-b97c-b5dde23af1f9-lun-010.0.0.146",
"Capacity": "2147483648",
"Guest_Device_Name": "vdb",
"IO_Operations": "93",
"Bytes_Written": "0",
"Bytes_Read": "380928"
}
}
}

查询数据的代码:

def counterVolume_one():
#Get data
url = 'http://url:8080/vrio/blk'
r = requests.get(url)
data = r.json()

wanted = {'Bytes_Written', 'Bytes_Written', 'IO_Operation'}
for d in data['Block Devices'].itervalues():
values = {k: v for k, v in d.iteritems() if k in wanted}
print json.dumps(values)

counterVolume_one()

我想要获得输出的方式是:

{"IO_Operations": "97069", "Bytes_Read": "363172864", "Bytes_Written": "34410496"}
{"IO_Operations": "93", "Bytes_Read": "380928", "Bytes_Written": "0"}

这是我想要完成的任务:

first time query = first set of values
after 1 sec
second time query = first set of values-second set of values
after 1 sec
third time query = second set of values-third set of values

预期输出将是如下所示的 json 对象

{'bytes-read': newvalue, 'bytes-written': newvalue, 'io_operations': newvalue}

最佳答案

最简单的修复方法可能是修改 counterVolume_one() 函数,使其接受定义当前状态的参数,并在收集数据时更新该参数。例如,以下代码从 JSON 文档中收集您感兴趣的字段并对其求和:

FIELDS = ('Bytes_Written', 'Bytes_Read', 'IO_Operation')

def counterVolume_one(state):
url = 'http://url:8080/vrio/blk'
r = requests.get(url)
data = r.json()

for field in FIELDS:
state[field] += data[field]
return state

state = {"Bytes_Written": 0, "Bytes_Read": 0, "IO_Operation": 0}
while True:
counterVolume_one(state)
time.sleep(1)
for field in FIELDS:
print("{field:s}: {count:d}".format(field=field,
count=state[field]))

更正确的解决方法可能是使用一个类来保存状态,并且该类具有更新状态的方法。但是,我认为遵循上述想法将使您最快地找到解决方案。

关于python - 如何创建一个在每次调用时从先前值中减去当前值的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33089888/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com