在规定的时间段执行操作?

Performing operations at defined periods?

我的脚本有问题,它计算数据库的平均值。

代码如下:

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()

用户需要输入--time参数来定义时间延迟。例如:

my_script.py -i localhost -c -t 60

我需要三个时间段 - 1 / 15 / 60 分钟。

如何在不使用很多 if 语句的情况下正确编写它?

您可以接受所有间隔作为命令行参数并循环遍历它们,或者,如果它们以某种方式相关并且可以从彼此派生,则编写一个函数来进行转换。