我正在用 Python 编写程序,它能够在某种沙箱中运行不受信任的 Python 代码。因此,我需要一种方法来限制不受信任的代码可以分配的内存量。现在,我可以通过覆盖沙盒环境中的默认 Python 数据结构来限制 range()、列表、字典和其他函数的最大长度。
有什么想法吗?
最佳答案
在 Unix 下,你可以使用 resource.setrlimit(resource.RLIMIT_AS, ...)限制 “进程可能占用的地址空间的最大区域(以字节为单位)。”
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 - 如何在 python 中为线程或进程设置内存限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16779497/