自动Suspend CPU占用率最高进程,夏天CPU好帮手

来源:互联网 发布:freehand for mac 编辑:程序博客网 时间:2024/04/29 15:02

内容如代码所示,温度和suspend、resume策略你需要自己修改一下:


#!/usr/bin/env python# -*- coding=utf-8 -*-import commands, signal, time, os, realarm_temp = 90safe_temp = 70ignore_cpu_percent = 10.0pid_pool = []my_name = ""def resume_one():    global pid_pool    if len(pid_pool) == 0:        return    pid = pid_pool[0]    os.kill(pid, signal.SIGCONT)    print "Resumed ", pid, " at ", time.strftime('%X %x %Z')    pid_pool.remove(pid)def suspend_one():    global pid_pool, myname    statue, output = commands.getstatusoutput('ps -eo "%C;%p;%u"')    p = re.compile("([0-9\.]+); *?([0-9\.]+);(.*)")    m = p.findall(output)    if len(m) == 0:        return    m.sort(lambda a,b: -cmp(float(a[0]),float(b[0])))    for item in m:        cpu = float(item[0])        pid = int(item[1])        user = item[2]        if user != my_name:            continue        if cpu <= ignore_cpu_percent:            return        if pid in pid_pool:            continue        os.kill(pid, signal.SIGSTOP)        print "Suspended", pid, " at ", time.strftime('%X %x %Z')        pid_pool.append(pid)        time.sleep(10)        return    def resume_all():    global pid_pool    for pid in pid_pool:        os.kill(pid, signal.SIGCONT)        print "Resumed", pid, " at ", time.strftime('%X %x %Z')    pid_pool = []def sigint_handler(signum = 0, e = 0):    resume_all()    exit(1)def get_temp():    statue, output = commands.getstatusoutput("sensors")    p = re.compile("temp1:.*?\+(.*?)°C")    m = p.findall(output)    if len(m) > 0:        return float(m[0])    else:        return 0def get_my_name():    global my_name    statue, output = commands.getstatusoutput("whoami")    my_name = outputif __name__ == '__main__':    get_my_name()    signal.signal(signal.SIGINT, sigint_handler)    while True:        temp = get_temp()        if temp >= alarm_temp:            suspend_one()        elif temp <= safe_temp:            resume_one()        time.sleep(1)


原创粉丝点击