python - 如何在 python 中为线程或进程设置内存限制?

标签 python multithreading python-2.7 cross-platform

我正在用 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/

相关文章:

java - Hadoop Hbase查询

python-2.7 - python ff-mpeg 在虚拟机上不起作用

c++ - 为 SWIG 指定 Python header 和库

python - 如何将 Python 的操作系统退出代码转换为其字符串值

python - 拆分总和 K 方式组合数学 python

python - 如何解决这个 bash python 交互?

Python_根据 Pandas 数据帧中的所有值执行特定行

mysql - 如何锁定 DBIx :Class? 中的表

C#每秒运行一个函数的最佳方式,定时器与线程?

c++ - 使用 Code::Blocks GNU 编译器编译多线程代码