python脚本提高linux内存占用率

/ 0评 / 0

直接上代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import re
import time

"""
python consume_men.py 100MB 1D
python consume_men.py 1GB 1M
第一个参数:表示消耗多少内存(MB/GB)
第二个参数:表示脚本需要执行多长时间
        Y:年
        M:月
        D:日
        H:小时
"""


def print_help():
    print('Usage: ')
    print('python consume_men.py 100MB 1D')
    print('python consume_men.py 1GB 1M')


if __name__ == "__main__":
    print('输入参数:{}'.format(sys.argv))
    # 获取参数
    try:
        free_arg = sys.argv[1].upper()
    except Exception:
        free_arg = '10GB'

    try:
        sleep_arg = sys.argv[2].upper()
    except Exception:
        sleep_arg = '1Y'

    pattern = re.compile('^(\d*)([M|G]B)')
    match = pattern.match(free_arg)
    if match:
        num = int(match.group(1))
        unit = match.group(2)
        try:
            if unit == 'MB':
                s = ' ' * (num * 1024 * 1024)
            else:
                s = ' ' * (num * 1024 * 1024 * 1024)
            print("消耗:"+free_arg+"内存...")
        except MemoryError:
            print("剩余内存不足,内存有溢出......")
    else:
        print_help()

    pattern = re.compile('^(\d*)([Y|M|D|H])')
    match = pattern.match(sleep_arg)
    if match:
        num = int(match.group(1))
        unit = match.group(2)
        if unit == 'Y':
            time_sleep_num = num * 12 * 30 * 24 * 60 * 60
        elif unit == 'M':
            time_sleep_num = num * 30 * 24 * 60 * 60
        elif unit == 'D':
            time_sleep_num = num * 24 * 60 * 60
        else:
            time_sleep_num = num * 60 * 60
        print("休眠:"+str(time_sleep_num)+"秒")
        time.sleep(time_sleep_num)
    else:
        print_help()

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注