简体   繁体   English

如果内存消耗过高,python 会中断进程

[英]python break process if memory consumption is to high

I am using a module and sometimes it crashes, because of memory consumption.我正在使用一个模块,有时它会因为内存消耗而崩溃。 It is terminated by SIGKILL 9 and the script is interrupted.它被 SIGKILL 9 终止,脚本被中断。 However I cannot access the loop in which the memory consumption happens.但是我无法访问发生内存消耗的循环。

This is how it looks now:这是它现在的样子:

import module
output = module.function(args)

and this sort of how it should look like:以及它应该是什么样子的:

import module
if ramconsumption(module.function(args)) > 999:
     output = None
else:
     output = module.function(args)

Do you know a way on how to implement this?你知道如何实现这一点吗? My example is just for better understanding, the solution should just be one where I do not get a SIGKILL, when too much memory is consumed.我的示例只是为了更好地理解,解决方案应该只是在消耗太多内存时我没有得到 SIGKILL 的解决方案。

This might work:这可能有效:

import os
import psutil
import module
import threading

def checkMemory():
    while True:
        process = psutil.Process(os.getpid())
        memoryUsage = process.memory_info().rss #in bytes
        if memoryUsage > amount:
            print("Memory budget exceeded")
            break
    os._exit(0)

threading.Thread(name="Memory Regulator", target=checkMemory).start()

output = module.function(args)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM