【问题标题】:python break process if memory consumption is to high如果内存消耗过高,python会中断进程
【发布时间】:2020-04-02 15:05:32
【问题描述】:

我正在使用一个模块,但由于内存消耗,有时它会崩溃。它被 SIGKILL 9 终止并且脚本被中断。但是我无法访问发生内存消耗的循环。

这就是现在的样子:

import module
output = module.function(args)

它应该是这样的:

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

您知道如何实现这一点吗?我的示例只是为了更好地理解,解决方案应该只是在消耗过多内存时我没有得到 SIGKILL 的解决方案。

【问题讨论】:

    标签: python ram sigkill


    【解决方案1】:

    这可能有效:

    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)
    

    【讨论】:

    • 我想这会在我的函数之前或之后。如果是这样,这将毫无用处,因为正是这个功能导致了问题,并且没有围绕它的循环
    • 你可以简单地在调用你的函数之前用一个线程来启动它,像这样:threading.Thread(name="Memory Regulator", target=checkMemory()).start()这将导致函数连续运行。
    猜你喜欢
    • 2011-06-01
    • 1970-01-01
    • 2022-06-14
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多