Search code examples
pythonloopstimeargs

Performing operations at defined periods?


I have problem with my script which is counting average mean from database.

Here is the code:

import MySQLdb
import argparse
import time

#args section
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--ip", required=True)
parser.add_argument("-r", "--ram", action="store_true", required=False)
parser.add_argument("-c", "--cpu", action="store_true", required=False)
parser.add_argument("-t", "--time", type=int, required=True)

args = parser.parse_args()

db1 = MySQLdb.connect(args.ip ,user="root",passwd="root")
cursor = db1.cursor()
use_db = "USE env_data;"

starttime = time.time()

def one_min():
        one_minute = time.sleep(60.0 - ((time.time() - starttime) % 60.0))
        return one_minute


def cpu_usage():
        cpu_select = "SELECT cpu_usage FROM env_data;"
        cpu_avg = "SELECT SUM(cpu_usage) / count(cpu_usage) from env_data;"

        cursor.execute(use_db)
        cursor.execute(cpu_select)
        cursor.execute(cpu_avg)
        result = cursor.fetchall()

        result = str(result)    #converted to string for replace operations
        for i in ['(',')',',', "'",'[', ']']:
                if i in result:
                        result = result.replace(i, '' )

        print result


def ram_usage():
        mem_select = "SELECT mem_usage FROM env_data;"
        mem_avg = "SELECT SUM(mem_usage) / count(mem_usage) from env_data;"

        cursor.execute(use_db)
        cursor.execute(mem_select)
        cursor.execute(mem_avg)
        result = cursor.fetchall()

        result = str(result)
        for i in ['(',')',',', "'",'[', ']']:
                if i in result:
                        result = result.replace(i, '' )

        print result

if args.cpu:
        cpu_usage()
elif args.ram:
        ram_usage()

User needs to type --time argument to define the time delay. For example:

my_script.py -i localhost -c -t 60

I need to have three periods - 1 / 15 / 60 minutes.

How I should to write it properly without using many if statements?


Solution

  • You can accept all there intervals as command line arguments and just loop over them or, if they somehow are related and can be derived from one another, write a function that does the conversion.