You could use resource
module to limit resources available to your process and its children.
If you need to decompress in memory then you could set resource.RLIMIT_AS
(or RLIMIT_DATA
, RLIMIT_STACK
) e.g., using a context manager to automatically restore it to a previous value:
import contextlib
import resource
@contextlib.contextmanager
def limit(limit, type=resource.RLIMIT_AS):
soft_limit, hard_limit = resource.getrlimit(type)
resource.setrlimit(type, (limit, hard_limit)) # set soft limit
try:
yield
finally:
resource.setrlimit(type, (soft_limit, hard_limit)) # restore
with limit(1 << 30): # 1GB
# do the thing that might try to consume all memory
If the limit is reached; MemoryError
is raised.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…