确定Python的最大有效setrecursionlimit值

在 Python 2文档中,sys库包含以下内容(粗体部分是我的编辑):

sys.setrecursionlimit(限制)

Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.

The highest possible limit is platform-dependent. A user may need to set the limit higher when she has a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.

这是什么意思?这只是一个通用的“确保你有足够的内存来处理额外的堆栈空间”声明,还是有一个特定的“每堆栈帧”大小可以用来计算所需的内存值?当Python无法获取空间时会发生什么?

最佳答案 为什么让我们发现:

me@host$docker run -m 4MB --cpuset-cpus=0 -it --rm python:3.5.1
Python 3.5.1 (default, Dec  9 2015, 00:12:22)
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys, struct
>>> maxint = 2 ** (struct.Struct('i').size * 8 - 1) - 1
>>> sys.setrecursionlimit(maxint)
>>> def goodbye_world():
...  goodbye_world()
...
>>> goodbye_world()
me@host$

韦尔普.看起来它崩溃了Python.当你只给它4MB的RAM时,也很快.

点赞