Limit RAM usage to python program

后端 未结 3 1273
梦如初夏
梦如初夏 2020-11-27 17:19

I\'m trying to limit the RAM usage from a Python program to half so it doesn\'t totally freezes when all the RAM is used, for this I\'m using the following code which is not

3条回答
  •  醉梦人生
    2020-11-27 17:48

    Ok so I've made some research and found a function to get the memory from Linux systems here: Determine free RAM in Python and I modified it a bit to get just the free memory available and set the maximum memory available as its half.

    Code:

    def memory_limit():
        soft, hard = resource.getrlimit(resource.RLIMIT_AS)
        resource.setrlimit(resource.RLIMIT_AS, (get_memory() * 1024 / 2, hard))
    
    def get_memory():
        with open('/proc/meminfo', 'r') as mem:
            free_memory = 0
            for i in mem:
                sline = i.split()
                if str(sline[0]) in ('MemFree:', 'Buffers:', 'Cached:'):
                    free_memory += int(sline[1])
        return free_memory
    
    if __name__ == '__main__':
        memory_limit() # Limitates maximun memory usage to half
        try:
            main()
        except MemoryError:
            sys.stderr.write('\n\nERROR: Memory Exception\n')
            sys.exit(1)
    

    The line to set it to the half is resource.setrlimit(resource.RLIMIT_AS, (get_memory() * 1024 / 2, hard)) where get_memory() * 1024 / 2 sets it to the half (it's in bytes).

    Hope this can help others in future with the same matter! =)

提交回复
热议问题