限制Python虚拟机内存

20 投票
3 回答
14585 浏览
提问于 2025-04-15 16:09

我想找个办法来限制Python虚拟机可以使用的内存,就像Java虚拟机里的“-Xmx”选项那样。(我的想法是能通过这个来玩一下MemoryError这个异常)

我不确定是否有这样的选项,但可能可以通过操作系统的某个命令来“隔离”一个进程及其内存。

谢谢。

3 个回答

3

别在这上面浪费时间了。

如果你想玩玩 MemoryError 这种错误,建议你设计一个可以单独测试对象创建的方式。

不要这样做:

for i in range(1000000000000000000000):
    try:
        y = AnotherClass()
    except MemoryError:
        # the thing we wanted to test

试试这样:

for i in range(1000000000000000000000):
    try:
        y = makeAnotherClass()
    except MemoryError:
        # the thing we wanted to test

这只需要在你的设计中加一个小小的改动。

class AnotherClass( object ):
    def __init__( self, *args, **kw ):
    blah blah blah

def makeAnotherClass( *args, **kw ):
    return AnotherClass( *args, **kw )

这个额外的功能,从长远来看,是个不错的设计模式。它叫做工厂模式,你经常会需要类似的东西。

然后你可以把这个 makeAnotherClass 替换成这样的东西:

class Maker( object ):
    def __init__( self, count= 12 ):
        self.count= count
    def __call__( self, *args, **kw ):
        if self.count == 0:
            raise MemoryError
        self.count -= 1
        return AnotherClass( *args, **kw )
 makeAnotherClass= Maker( count=12 )

这个版本会抛出一个错误,而不需要你以任何复杂、难以理解或神秘的方式来限制内存。

34

在Linux系统上,我正在使用resource模块:

import resource
resource.setrlimit(resource.RLIMIT_AS, (megs * 1048576L, -1L))
12

在*nix系统上,你可以使用ulimit这个命令来进行一些操作,特别是可以调整两个参数:-m(最大内存大小)和-v(虚拟内存)。

撰写回答