Setting maximum RAM usage for an interactive session in Pydev

Is there a way to set the maximum allowed RAM usage in an interactive PyDev session? My computer has a tendency to freeze if I accidentally find a command that causes the RAM to swell.

+3


source to share


1 answer


On Unix, you can limit the amount of resources (such as memory) available to a process using resource.setrlimit . For example, to limit the maximum address space to 10 ** 6 bytes:

import sys
import resource

resource.setrlimit(resource.RLIMIT_AS, (10 ** 6, 10 ** 6))
memory_hog = {}
try:
    for x in range(10000):
        memory_hog[str(x)] = 'The sky is so blue'
except MemoryError as err:
    sys.exit('memory exceeded')
    # memory exceeded

      

resource.setrlimit

Appears when called MemoryError

because it memory_hog

takes up too much space. Without the call, the resource.setrlimit

program should exit normally (on normal hardware).


You can also limit the total CPU time available with:

resource.setrlimit(resource.RLIMIT_CPU, (n, n))

      



where n

is set in seconds. For example,

In [1]: import math

In [2]: x = math.factorial(40000)

In [3]: import resource

In [4]: resource.setrlimit(resource.RLIMIT_CPU, (2, 2))

In [5]: x = math.factorial(40000)

Process Python killed

      

The process was killed as it couldn't compute 40000!

after 2 seconds.


Note that both of these commands affect the entire PyDev session, not just one command.

+3


source







All Articles