将RAM使用限制为python程序

2024-05-29 06:57:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将一个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)

我正在使用从main函数调用的其他函数。

我做错什么了?

提前谢谢。

警察:我已经搜过了,找到了我放的代码,但还是不行。。。


Tags: 代码import程序maindefsysresourceram
3条回答

我修改了@Ulises CT的答案。因为我觉得改变太多原来的功能不是那么好,所以我把它变成了一个装饰。我希望有帮助。

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%.')

好吧,我做了一些研究,找到了一个从Linux系统中获取内存的函数:Determine free RAM in Python,我对它进行了一些修改,只获取可用的空闲内存,并将可用的最大内存设置为它的一半。

代码:

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)

将其设置为一半的行是resource.setrlimit(resource.RLIMIT_AS, (get_memory() * 1024 / 2, hard)),其中get_memory() * 1024 / 2将其设置为一半(以字节为单位)。

希望这可以帮助其他人在未来同一件事!=)

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

最好使用:

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

在一台1TB内存的机器上,答案代码为我提供了8GB的可用内存

相关问题 更多 >

    热门问题