如何在python中设置线程或进程的内存限制? [英] How to set memory limit for thread or process in python?

查看:261
本文介绍了如何在python中设置线程或进程的内存限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Python编写程序,该程序将能够在某种沙箱中运行不受信任的python代码.因此,我需要一种方法来限制不受信任的代码可以分配的内存量.现在,我可以通过覆盖沙盒环境中的默认python数据结构来限制range(),列表,字典和其他对象的最大长度.

I'm writing program in Python which would be able to run untrusted python code in some kind of sandbox. So, I need a way to limit the amount of memory that untrusted code can allocate. At now I can limit the maximum length of range(), list, dictionary and the others by overriding default python data structures in my sandboxed environment.

有什么想法吗?

推荐答案

在Unix下,您可以使用 resource.setrlimit(resource.RLIMIT_AS,...)进行限制 进程可能占用的地址空间的最大区域(以字节为单位)."

Under Unix, you could use resource.setrlimit(resource.RLIMIT_AS, ...) to restrict "the maximum area (in bytes) of address space which may be taken by the process."

import sys
import resource
soft, hard = 10**7, 10**7
# soft, hard = 10**8, 10**8   # uncommenting this allows program to finish
resource.setrlimit(resource.RLIMIT_AS,(soft, hard))
memory_hog = {}
try:
    for x in range(10000):
        print(x)
        memory_hog[str(x)]='The sky is so blue'
except MemoryError as err:
    sys.exit('memory exceeded')
    # memory exceeded

这篇关于如何在python中设置线程或进程的内存限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆