python 最大递归次数 RuntimeError: maximum recursion depth exceeded

转载 2018年04月15日 22:31:30

转载出处:点击打开链接

帮别人看代码,偶然遇到这个问题,原来python解释器有一个默认的最大递归次数是999。

举个例子:

def recursion(n):
    if (n <= 1):
        return
    print n
    recursion(n - 1)

print "test 999"
recursion(999)   #正常运行

print "test 1000"
recursion(1000)  #报错,RuntimeError: maximum recursion depth exceeded
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

可以在文件初始位置修改这个最大递归次数,如下:

import sys
sys.setrecursionlimit(10000)  # set the maximum depth as 10000
  • 1
  • 2
  • 3

这时候递归1000次,2000次都不会报错了,但次数很大时比如5000就会报错,又查资料,结论如下:

sys.setrecursionlimit(limit) 
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.

sys.setrecursionlimit() 只是修改解释器在解释时允许的最大递归次数,此外,限制最大递归次数的还和操作系统有关,经过测试:

windows下最大迭代次数约4400次,linux下最大迭代次数约为24900次(python 2.7 64位)

如下代码可以测试最大迭代次数:


import sys
import itertools

class RecursiveBlowup1:
    def __init__(self):
        self.__init__()

def test_init():
    return RecursiveBlowup1()

class RecursiveBlowup2:
    def __repr__(self):
        return repr(self)

def test_repr():
    return repr(RecursiveBlowup2())

class RecursiveBlowup4:
    def __add__(self, x):
        return x + self

def test_add():
    return RecursiveBlowup4() + RecursiveBlowup4()

class RecursiveBlowup5:
    def __getattr__(self, attr):
        return getattr(self, attr)

def test_getattr():
    return RecursiveBlowup5().attr

class RecursiveBlowup6:
    def __getitem__(self, item):
        return self[item - 2] + self[item - 1]

def test_getitem():
    return RecursiveBlowup6()[5]

def test_recurse():
    return test_recurse()

def test_cpickle(_cache={}):
    try:
        import cPickle
    except ImportError:
        print "cannot import cPickle, skipped!"
        return
    l = None
    for n in itertools.count():
        try:
            l = _cache[n]
            continue  # Already tried and it works, let's save some time
        except KeyError:
            for i in range(100):
                l = [l]
        cPickle.dumps(l, protocol=-1)
        _cache[n] = l

def check_limit(n, test_func_name):
    sys.setrecursionlimit(n)
    if test_func_name.startswith("test_"):
        print test_func_name[5:]
    else:
        print test_func_name
    test_func = globals()[test_func_name]
    try:
        test_func()
    # AttributeError can be raised because of the way e.g. PyDict_GetItem()
    # silences all exceptions and returns NULL, which is usually interpreted
    # as "missing attribute".
    except (RuntimeError, AttributeError):
        pass
    else:
        print "Yikes!"

limit = 1000
while 1:
    check_limit(limit, "test_recurse")
    # check_limit(limit, "test_add")
    # check_limit(limit, "test_repr")
    # check_limit(limit, "test_init")
    # check_limit(limit, "test_getattr")
    # check_limit(limit, "test_getitem")
    # check_limit(limit, "test_cpickle")
    print "Limit of %d is fine" % limit
    limit = limit + 100

python递归深度报错--RuntimeError: maximum recursion depth exceeded

问题这段时间用Python写了一个爬虫脚本,在抓取页面采用广度优先遍历抓取。但是当遍历到1000左右时就会出现莫名其妙的错误, 通过pdb调试发现是:RuntimeError: maximum re...
  • gatieme
  • gatieme
  • 2015-12-31 22:33:32
  • 11160

python递归深度报错: RuntimeError: maximum recursion depth exceeded

这段时间用Python写了一个爬虫脚本,在抓取页面采用广度优先遍历抓取。但是当遍历到900多时就会出现莫名其妙的错误,通过pdb调试发现是:RuntimeError: maximum recursio...
  • Jesounao
  • Jesounao
  • 2016-03-21 11:20:01
  • 560

python RuntimeError: maximum recursion depth exceeded

使用 python做爬虫时遇到 RuntimeError: maximum recursion depth exceeded; 原因:python默认的递归深度是很有限的,1000左右 解决办法之...
  • chenqiangdage
  • chenqiangdage
  • 2016-04-14 23:37:45
  • 897

Python RuntimeError: maximum recursion depth exceeded in cmp 超过最大递归深度错误

说明:Python运行版本Python2.7.12 最近写了个Python爬虫,运行时出现 RuntimeError: maximum recursion depth exceeded in cmp...
  • xfyangle
  • xfyangle
  • 2017-02-24 14:52:57
  • 829

RuntimeError: maximum recursion depth exceeded 递归深度报错

我想把Python中的递归作为一个专题讨论一下。我在学习的时候,尝试使用“Python递归”作为关键词,在Google和百度中搜索,发现结果大部分是对某个具体例子的递归应用讨论,而对我这样的小白来说,...
  • welber
  • welber
  • 2011-05-26 14:44:00
  • 21948

django启动的时候报错RuntimeError: maximum recursion depth exceeded in cmp

django启动的时候报了错 py2.7,django1.9 python manage.py runserver 报错如下: Unhandled except...
  • u013632854
  • u013632854
  • 2017-04-14 20:02:27
  • 1756

Django启动服务器报错:maximum recursion depth exceeded in cmp

解决方案: 找到路径 python\Lib\fuctools.py: 将如下内容: convert = { '__lt__': [('__gt__', lambda self, othe...
  • liwei825755184
  • liwei825755184
  • 2017-08-19 17:33:22
  • 440

matplotlib画图异常--超出最大递归次数解决办法

最近在练习一个回归方程,使用python的matplotlib库画图,再将回归直线显示的过程中,出现异常: File "D:\Python27\lib\site-packages\matplotl...
  • u012293522
  • u012293522
  • 2015-06-13 10:39:58
  • 648

python setup.py install 出现了 RuntimeError: maximum recursion depth exceeded in cmp

Processing setuptools-34.3.3.zip Writing /tmp/easy_install-1u8rIK/setuptools-34.3.3/setup.cfg Runn...
  • u013176681
  • u013176681
  • 2017-03-31 10:22:55
  • 1045

win10启动django项目报错 Django RuntimeError: maximum recursion depth exceeded

来源自我的博客 错误:Django RuntimeError: maximum recursion depth exceeded原因出自python\Lib\fuctools.py 把conv...
  • yingzinanfei
  • yingzinanfei
  • 2017-02-04 13:30:07
  • 781
收藏助手
不良信息举报
您举报文章:python 最大递归次数 RuntimeError: maximum recursion depth exceeded
举报原因:
原因补充:

(最多只允许输入30个字)