简体   繁体   English

将RAM的使用限制为python程序

[英]Limit RAM usage to python program

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 working and my laptop is still freezing: 我试图将Python程序的RAM使用量限制为一半,以便在使用所有RAM时都不会完全冻结,为此,我正在使用以下代码,该代码无法正常工作,并且笔记本电脑仍在冻结:

import sys
import resource

def memory_limit():
    rsrc = resource.RLIMIT_DATA
    soft, hard = resource.getrlimit(rsrc)
    soft /= 2
    resource.setrlimit(rsrc, (soft, hard))

if __name__ == '__main__':
    memory_limit() # Limitates maximun memory usage to half
    try:
        main()
    except MemoryError:
        sys.stderr.write('MAXIMUM MEMORY EXCEEDED')
        sys.exit(-1)

I'm using other functions which I call from the main function. 我正在使用从main函数调用的其他函数。

What am I doing wrong? 我究竟做错了什么?

Thanks in advance. 提前致谢。

PD: I already searched about this and found the code I've put but it's still not working... PD:我已经搜索了一下,找到了我输入的代码,但是仍然无法正常工作...

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. 好的,所以我进行了一些研究,找到了一个从Linux系统获取内存的函数: 在Python中确定可用RAM,然后我对其进行了一些修改,以获取可用内存并将最大可用内存设置为一半。

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). 将其设置为一半的行是resource.setrlimit(resource.RLIMIT_AS, (get_memory() * 1024 / 2, hard)) ,其中get_memory() * 1024 / 2将其设置为一半(以字节为单位)。

Hope this can help others in future with the same matter! 希望以后可以在同一件事上帮助他人! =) =)

due to https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773 由于https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773

it is better to use : 最好使用:

if str(sline[0]) == 'MemAvailable:':
            free_memory = int(sline[1])
            break

the answer code provided me with 8 GB of available mem on a machine with 1TB of RAM 答案代码在具有1TB RAM的计算机上为我提供了8 GB可用内存

I modify the answer of @Ulises CT. 我修改了@Ulises CT的答案。 Because I think to change too much original function is not so good, so I turn it to a decorator. 因为我认为更改太多原始功能不是很好,所以我将其转为装饰器。 I hope it helps. 希望对您有所帮助。

import resource
import platform
import sys

def memory_limit(percentage: float):
    """
    只在linux操作系统起作用
    """
    if platform.system() != "Linux":
        print('Only works on linux!')
        return
    soft, hard = resource.getrlimit(resource.RLIMIT_AS)
    resource.setrlimit(resource.RLIMIT_AS, (get_memory() * 1024 * percentage, 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

def memory(percentage=0.8):
    def decorator(function):
        def wrapper(*args, **kwargs):
            memory_limit(percentage)
            try:
                function(*args, **kwargs)
            except MemoryError:
                mem = get_memory() / 1024 /1024
                print('Remain: %.2f GB' % mem)
                sys.stderr.write('\n\nERROR: Memory Exception\n')
                sys.exit(1)
        return wrapper
    return decorator

@memory(percentage=0.8)
def main():
    print('My memory is limited to 80%.')

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

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