#!/usr/bin/env python3 # # Limits the maximal virtual memory for a subprocess in Python. # # Linux only. # import subprocess import resource # Maximal virtual memory for subprocesses (in bytes). MAX_VIRTUAL_MEMORY = 10 * 1024 * 1024 # 10 MB def limit_virtual_memory(): # The tuple below is of the form (soft limit, hard limit). Limit only # the soft part so that the limit can be increased later (setting also # the hard limit would prevent that). # When the limit cannot be changed, setrlimit() raises ValueError. resource.setrlimit(resource.RLIMIT_AS, (MAX_VIRTUAL_MEMORY, resource.RLIM_INFINITY)) p = subprocess.Popen( ['ls', '-l', '/'], # preexec_fn is a callable object that will be called in the child process # just before the child is executed. preexec_fn=limit_virtual_memory ) p.communicate()