How to limit the heap size?

Check out resource.setrlimit(). It only works on Unix systems but it seems like it might be what you’re looking for, as you can choose a maximum heap size for your process and your process’s children with the resource.RLIMIT_DATA parameter.

EDIT: Adding an example:

import resource

rsrc = resource.RLIMIT_DATA
soft, hard = resource.getrlimit(rsrc)
print 'Soft limit starts as  :', soft

resource.setrlimit(rsrc, (1024, hard)) #limit to one kilobyte

soft, hard = resource.getrlimit(rsrc)
print 'Soft limit changed to :', soft

I’m not sure what your use case is exactly but it’s possible you need to place a limit on the size of the stack instead with resouce.RLIMIT_STACK. Going past this limit will send a SIGSEGV signal to your process, and to handle it you will need to employ an alternate signal stack as described in the setrlimit Linux manpage. I’m not sure if sigaltstack is implemented in python, though, so that could prove difficult if you want to recover from going over this boundary.

Leave a Comment