имеется код, благодаря которому значению присваивается две строки, например:
11111111111
1111111
Но enumerate выдает номер строки нулевой для обеих, разбить с помощью split/strip и т.п. не может…
Нужна помощь)
Есть второй вариант решения-код сам работает, но данные выводятся сначала правильно с первой строкой (data), а далее вторая строка значений заменяет не то, что надо….. т.е. с первой строкой действия верные. вторая либо просто не выводится, либо выводится, но считается всё неверно….вывод напишу в конце…
В общих чертах - есть команда в ком. строке, которая выводит таблицу, данные из которой я вытягиваю. причем данные мне нужно вытягивать вне зависимости от количества строк с необходимыми данными. вот сама команда и ее вывод:
~ $ rados df
pool name KB objects clones degraded unfound rd rd KB wr wr KB
data 1204848704 21555277 0 0 0 139022 92444082 52700900 1550153369
metadata 41535 350387 0 0 0 1334312 3670751833 123883000 401565390
total used 4166216120 21905664
total avail 6217083240
total space 10939188688
вот сам код:
# -*- coding: utf-8 -*- import os import json import re import tempfile import subprocess import sys import time import fileinput from sensu_plugin import SensuPluginMetricGraphite from datetime import datetime #class CephMetrics(SensuPluginMetricGraphite): data = { 'rd': 0, 'rd KB': 0, 'wr': 0, 'wr KB': 0, 'time':0 } work_data = { 'rd': 0, 'rd KB': 0, 'wr': 0, 'wr KB': 0, 'time':0 } new_data = { 'rd': 0, 'rd KB': 0, 'wr': 0, 'wr KB': 0, 'time':0 } # def run(self): # mass_slovar = [] first_data = False tmp_file = tempfile.gettempdir() + '/' + 'ceph.stats.tmp' mode = 'r+' if os.path.exists(tmp_file) else 'w+' prev_data_file = open(tmp_file, mode) try: old_data = json.loads(''.join(prev_data_file.readlines())) except ValueError: first_data = True #old_data = work_data old_time = old_data['time'] print ("old time", old_time) atime = str(time.time()) now_time = ("%d" % (float(atime))) print ("new time", now_time) time_difference = (int(now_time) - int(old_time)) print ("time difference %d %s" %(time_difference, 'seconds')) print ("\n") c = subprocess.Popen("rados df".split(" "), stdout=subprocess.PIPE, stderr=subprocess.PIPE) text = c.stdout.read() for textline in text.split("\n"): stline = textline.strip() if len(stline) > 1 and not stline.startswith('pool') and not stline.startswith('total'): stline = re.split("\s+", stline) #########где-то здесь должен быть более ровный код ######### текущему словарю new_data присваивается по два значения,которые мне по хорошему бы разбить и просуммировать/вычесть new_data = { 'rd': stline[6], 'rd KB': stline[7], 'wr': stline[8], 'wr KB': stline[9], 'time': now_time } print "\n" print new_data if not first_data: for k in work_data: try: work_data[k] = (int(new_data[k]) - int(old_data[k])) except KeyError: work_data[k] = 0 #print ("new time", now_time) print ("\n") print ("old data", old_data) print ("\n") print ("new data", new_data) print ("\n") PoolName = stline[0] print ('PoolName: ',PoolName) for k in work_data: print (' ' + k + ' ', work_data[k]) print ("\n") readspeed = work_data['rd KB'] writespeed = work_data['wr KB'] readops = work_data['rd'] writeops = work_data['wr'] if work_data['rd KB'] > 0: print("average read speed for the last %d %s %d %s" %(time_difference, " seconds is ", ((readspeed / time_difference)), "bytes/s")) print("total %d %s %d %s" %(readops, "read operations for last ", time_difference, " seconds")) print("total %d %s" %((readops/time_difference), " read op/s")) print "%5.2f" % (readops/time_difference) else: print('no read operations for the last time') print ("\n") if (work_data['wr KB']) > 0: print("average write speed for the last %d %s %d %s" %(time_difference, " seconds is ", ((writespeed / time_difference)), "bytes/s")) print("total %d %s %d %s" %(writeops, "write operations for last ",time_difference, " seconds")) print("total ???? %d %s" %((writeops/time_difference), " write op/s")) print "%5.2f" % (writeops/time_difference) else: print('no write operations for the last time') #print "\n prev_data_file.seek(0) prev_data_file.write(json.dumps(new_data)) prev_data_file.truncate() prev_data_file.close()
вот мой вывод:
/usr/bin/python2.7 /home/serg/PycharmProjects/untitled/234234234.py
('old time', u'1441344337')
('new time', ‘1441344625’)
time difference 288 seconds
{'rd': ‘139022’, ‘wr KB’: ‘1550153369’, ‘rd KB’: ‘92444082’, ‘wr’: ‘52700900’, ‘time’: ‘1441344625’}
('old data', {u'rd': u'1334312', u'wr KB': u'401565390', u'rd KB': u'3670751833', u'wr': u'123883000', u'time': u'1441344337'})
('new data', {'rd': ‘139022’, ‘wr KB’: ‘1550153369’, ‘rd KB’: ‘92444082’, ‘wr’: ‘52700900’, ‘time’: ‘1441344625’})
('PoolName: ‘, ’data')
(' rd ‘, -1195290)
(’ wr KB ‘, 1148587979)
(’ rd KB ‘, -3578307751)
(’ wr ‘, -71182100)
(’ time ‘, 288)
no read operations for the last time
###здесь у меня всякие проверки, особого внимания обращать не нужно
average write speed for the last 288 seconds is 3988152 bytes/s
total -71182100 write operations for last 288 seconds
total ???? -247161 write op/s
-247161.00
{’rd': ‘1334312’, ‘wr KB’: ‘401565390’, ‘rd KB’: ‘3670751833’, ‘wr’: ‘123883000’, ‘time’: ‘1441344625’}
('old data', {u'rd': u'1334312', u'wr KB': u'401565390', u'rd KB': u'3670751833', u'wr': u'123883000', u'time': u'1441344337'})
('new data', {'rd': ‘1334312’, ‘wr KB’: ‘401565390’, ‘rd KB’: ‘3670751833’, ‘wr’: ‘123883000’, ‘time’: ‘1441344625’})
('PoolName: ‘, ’metadata')
(' rd ‘, 0)
(’ wr KB ‘, 0)
(’ rd KB ‘, 0)
(’ wr ‘, 0)
(’ time ', 288)
no read operations for the last time
no write operations for the last time
Process finished with exit code 0