如何在 python 进程中限制内存使用

How to limit memory usage within a python process

I 运行 Python 2.7 在具有 16GB Ram 和 64 位 OS 的 Linux 机器上。我编写的 python 脚本可能会将太多数据加载到内存中,这会降低机器的速度,以至于我什至无法再终止进程。

虽然我可以通过调用来限制内存:

ulimit -v 12000000

在 shell 之前 运行 脚本中,我想在脚本本身中包含一个限制选项。在我看过的所有地方,resource 模块都被引用为与 ulimit 具有相同的功能。但是调用:

import resource
_, hard = resource.getrlimit(resource.RLIMIT_DATA)
resource.setrlimit(resource.RLIMIT_DATA, (12000, hard))

在我的脚本开头完全没有做任何事情。即使将值设置为低至 12000,也不会导致进程崩溃。我对 RLIMIT_STACK 进行了相同的尝试,结果也相同。奇怪的是,调用:

import subprocess
subprocess.call('ulimit -v 12000', shell=True)

也什么都不做。

我做错了什么?我在网上找不到任何实际使用示例。


编辑:对于好奇的人来说,使用 subprocess.call 不起作用,因为它创建了一个(惊喜,惊喜!)新进程,它独立于当前 python 程序的进程运行秒。

resource.RLIMIT_VMEM is the resource corresponding to ulimit -v.

RLIMIT_DATA only affects brk/sbrk system calls while newer memory managers tend to use mmap instead.

第二个要注意的是ulimit/setrlimit只影响当前进程和它未来的子进程。

关于 AttributeError: 'module' object has no attribute 'RLIMIT_VMEM' 消息:resource module docs 提到了这种可能性:

This module does not attempt to mask platform differences — symbols not defined for a platform will not be available from this module on that platform.

根据上面链接的 bash ulimit source,如果未定义 RLIMIT_VMEM,则使用 RLIMIT_AS