有没有办法在交互式 PyDev session 中设置允许的最大 RAM 使用量?如果我不小心键入导致 RAM 使用量膨胀的命令,我的计算机往往会挂起。
最佳答案
在 Unix 上,您可以使用 resource.setrlimit 限制进程可用的资源量(例如内存) .例如,要限制地址空间的最大区域为 10**6 字节:
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
,MemoryError
被引发,因为 memory_hog
占用太多空间。如果不调用 resource.setrlimit
,程序应该正常完成(在典型硬件上)。
您还可以限制可用的总 CPU 时间:
resource.setrlimit(resource.RLIMIT_CPU, (n, n))
其中 n
以秒为单位给出。例如,
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
进程被终止,因为它无法在 2 秒内计算出 40000!
。
请注意,这两个命令都会影响整个 PyDev session ,而不仅仅是一个命令。
关于python - 在 Pydev 中设置交互式 session 的最大 RAM 使用率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25709002/