首页 > 解决方案 > 限制脚本中的 Ram 使用

问题描述

我需要限制在 NiFi 中运行 Python 脚本时使用的内存量,我在 Stack Overflow 中找到了这个答案。我遵循代码如何工作的逻辑,但我对如何在 Python 脚本中实际实现它有点困惑。

例如,如果我有一个脚本

import sys
import json

flowFile = sys.stdin.read()
try: 
    j = json.loads(flowFile)
    sys.stdout.write(j)
except:
    sys.stdout.write(flowFile)

然后我会将内存限制实现为

import sys
import json

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)

flowFile = sys.stdin.read()
try: 
    j = json.loads(flowFile)
    sys.stdout.write(j)
except:
    sys.stdout.write(flowFile)

还是完全不同的东西?

标签: pythonram

解决方案


推荐阅读