python在服务器上跑了一段时间后,由于内存问题,老是要报警。查看了原因,是有些服务没有释放内存。此脚本可以通过重启进程服务来释放内存。
操作系统为: Linux x86_64 GNU/Linux
python版本为:2.7.2
相关的代码如下:
#!/usr/bin/env Python
#encoding=utf-8
from __future__ import print_function
from collections import OrderedDict
import os,sys,re,time,logging
reload(sys)
sys.setdefaultencoding('utf-8')
def meminfo():
meminfo = OrderedDict()
with open('/proc/meminfo') as f:
for line in f:
meminfo[line.split(':')[0]] = line.split(':')[1].strip()
return meminfo
def getNum(a=''):
num_model = re.compile(r'\d+')
if num_model.findall(a)[0]:
num = num_model.findall(a)[0]
else:
num = 0
return int(num)
if __name__=='__main__':
time2sleep = 25
check_list = [12,23] # 在 12,21点进行检测 ,其他时间不检测
while True:
try:
hours = int(time.strftime("%H", time.localtime(time.time())))
if check_list.count(hours) != 1: # 在1点后检查优化信息上线情况
print('时间没到,休息:{0}'.format(hours))
time.sleep(1800)
continue
this_meminfo = meminfo()
temp_mem = getNum(str(this_meminfo['MemFree']))
if temp_mem == 0:
continue
print('可用内存:{0}'.format(temp_mem))
if temp_mem > 2048000: #可用内存大于2G
print("sleep 1h")
time.sleep(3600)
continue
getNowTime = time.strftime("%Y%m%d%H%M", time.localtime(time.time()))
print('当前运行检测的时间:{0}'.format(getNowTime))
print('---------------------进程开始查询-------------------------')
str_temp = os.popen("ps -eo pid,pmem,args|grep python2.7|sort -k2 -r -n|head -n 3").read()
strSplit = str_temp.splitlines();
print('当前检测到的进程:{0}'.format(strSplit))
for result in strSplit:
if result:
print('当前循环原值{0}'.format(result))
mode = re.compile(r'\d+')
if mode.findall(result)[0]:
pid = mode.findall(result)[0] # 获取pid 杀死
com_mode = re.compile(r'.\/data\/(.*?)\.py')
if com_mode.findall(result)[0]:
old_com = com_mode.findall(result)[0]
if pid and old_com:
print('kill start:{0},id:{1}'.format(old_com,pid))
os.system("kill -9 " + pid)
print('-------------sleep start-------------')
time.sleep(time2sleep) #休息25s让进程检测服务启动进程
thread = old_com.split('/')[1]
new = "nohup python2.7 /data/"+ old_com.strip() +".py &"
is_run = os.popen('ps -ef|grep '+ thread +'.py|grep -v grep|wc -l').read()
print('当前进程{0},执行情况{1}'.format(new,is_run))
if is_run[0] =='0':
time.sleep(0.1)
os.system(new)
print('启动进程:{0}'.format(new))
logging.error("----time run "+ new +" --%s" % (getNowTime))
except Exception, e:
logging.error("run error==== --%s" % (str(e)))
pass