python手动垃圾回收_python垃圾回收,判断内存占用,手动回收内存,二

该博客主要介绍了如何使用Python进行内存监控,包括获取系统和指定进程的内存使用情况,以及实现手动内存回收。通过`psutil`库获取CPU和内存使用率,监控特定进程的资源消耗,并使用垃圾回收器`gc`进行内存释放。此外,还提供了实时监测内存的实用方法。
摘要由CSDN通过智能技术生成

#coding=utf8

importtimeimportpsutil, gc, commandsfrom logger_until importLoggerUntilfrom until importkeep_circulating

logger= LoggerUntil(name="Monitor").getlog(logfilename=‘Monitor.log‘, loglevel=2, add_StreamHandler=1)

need_monitor_procces_names= [ ##需要检测的进程的cmd命令放到这里,支持模糊匹配

‘touna0627.py‘,‘dailiip.py‘,‘redis-server‘,‘mongod‘,

]classMonitor(object):def __init__(self):

self.specified_process_list=self.get_specified_process()

self.current_process=self.get_current_process()

@staticmethoddefprint_all_cmdlines():for pid inpsutil.pids():

p=psutil.Process(pid)printp.cmdline()

@staticmethoddefget_specified_process():

all_pids=psutil.pids()

process_list=[]for pid inall_pids:

p=psutil.Process(pid)

p_cmdline=p.cmdline()for argx inp_cmdline:for name inneed_monitor_procces_names:if argx.find(name) > -1:if p.status() != ‘stopped‘:

process_list.append(p)

p_pid_set=set()

process_list2=[]for p inprocess_list:if p.pid not inp_pid_set:

process_list2.append(p)

p_pid_set.add(p.pid)returnprocess_list2

@staticmethoddefmonitor_system():

psutil.cpu_percent()

time.sleep(1)

mem=psutil.virtual_memory()

mem_total= mem.total / 1000000mem_available= mem.available / 1000000mem_percent_str= str(mem.percent) + ‘%‘cpu_count=psutil.cpu_count()

cpu_percent_str= str(psutil.cpu_percent()) + ‘%‘msg= ‘本机总内存是:{0}M , 本机可用内存是:{1}M, 本机内存使用率是:{2}, 本机cpu核数是:{3}, 本机cpu使用率是:{4}\n\n‘.format(mem_total, mem_available, mem_percent_str, cpu_count, cpu_percent_str)

logger.info(msg)defmonitor_specified_process(self):for p inself.specified_process_list:

p.cpu_percent(None)

time.sleep(1)for p inself.specified_process_list:#p = psutil.Process(0)

""":type :psutil.Process"""cmdline_str= ‘ ‘.join(p.cmdline()).ljust(60, ‘ ‘)

p_cpu_percent_str= str(round(p.cpu_percent(), 2)) + ‘%‘p_memory_percent_str= str(round(p.memory_percent(), 2)) + ‘%‘p_strated_time= time.strftime(‘%Y-%m-%d %H:%M:%S‘, time.localtime(p.create_time()))

p_pid_str=str(p.pid)

msg= ‘进程‘ + cmdline_str + ‘的pid是:‘ + p_pid_str + ‘cpu使用率是:‘ + p_cpu_percent_str + ‘内存使用率是:‘ +p_memory_percent_str+ ‘进程的启动时间是:‘ +p_strated_time

logger.info(msg)

@staticmethoddefget_current_process():returnpsutil.Process()defis_need_release(self,threshold):printself.current_process.memory_percent()if self.current_process.memory_percent()

logger.info(‘回收当前 %s 进程id的内存‘ %self.current_process.pid)return 1

deffree_current_process_memory(self, threshold):"""回收python所处的当前进程的内存"""

if self.is_need_release(threshold) == 1:

gc.collect()classMemoryReleaser():def __init__(self,threshold):

self.threshold=threshold

self.stutus, self.output= self.__get_memory_available()

@staticmethoddef __get_memory_available():

status, output= commands.getstatusoutput("free -m | grep Mem | awk ‘{print $7}‘") ##shell命令查询计算机可用内存returnstatus, outputdefrelease_memory(self):if float(self.output)

logger.info(‘计算机可用内存是 %sM ,程序需要释放内存‘%self.output)

gc.collect()

@keep_circulating(10)defmonitoring():

MemoryReleaser(600).release_memory() ###这一行来释放内存

monitor=Monitor()

monitor.monitor_specified_process()

monitor.monitor_system()if __name__ == "__main__":passa= list(range(10000000))dela

monitoring()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值