def limit_mem(limit=(4 * 1024**3)):
    "Set soft memory limit"
    rsrc = resource.RLIMIT_DATA
    soft, hard = resource.getrlimit(rsrc)
    resource.setrlimit(rsrc, (limit, hard))  # 4GB
    softnew, _ = resource.getrlimit(rsrc)
    assert softnew == limit

    _log = logging.getLogger(__name__)
    _log.debug('Set soft memory limit: %s => %s', soft, softnew)
Set soft memory limit