美文网首页
记一次python内存溢出

记一次python内存溢出

作者: 来一碗花甲粉 | 来源:发表于2019-04-23 11:04 被阅读0次

问题:

openxl在处理一个excel文件时,由于文件和库的问题,导致python占用内存飙升,不断增长,最终占满机器内存,并且挤掉了mongo服务 -.-!!!

解决:

表格返工处理了一下,问题解决,但这不是长久之计,于是考虑python内存管理,并设置内存上限,以防之后可能发生的异常

python如何限制内存和CPU的使用量

解决方案

resource 模块可以胜任这两个任务。
1.如下限制CPU运行时间:

import resource
import os

def time_exceeded(signo, frame):
   print("Time's up!")
   raise SystemExit(1)

def set_max_runtime(seconds):
   # Install the signal handler and set a resource limit
   soft, hard = resource.getrlimit(resource.RLIMIT_CPU)
   resource.setrlimit(resource.RLIMIT_CPU, (seconds, hard))
   signal.signal(signal.SIGXCPU, time_exceeded)

if __name__ == '__main__':
   set_max_runtime(15)
   while True:
       pass

程序运行,在时间过期后,生成SIGXCPU 信号,然后清理并退出程序。

2.如下 限制内存使用:

import resource

def limit_memory(maxsize):
    soft, hard = resource.getrlimit(resource.RLIMIT_AS)
    resource.setrlimit(resource.RLIMIT_AS, (maxsize, hard))

设置了内存限制后,程序运行到没有多余内存时会抛出 MemoryError 异常。

相关文章

网友评论

      本文标题:记一次python内存溢出

      本文链接:https://www.haomeiwen.com/subject/ysimgqtx.html