Python的最大递归深度错误 “maximum recursion depth exceeded while calling a Python object”

  今天在写爬虫的时候,发现了一个诡异的事情,使用str方法强制转换一个BeautifulSoup对象成字符串的时候报错了,提示是“maximum recursion depth exceeded while calling a Python object”,意思大致是“当调用该对象超过最大递归深度”

  报错如下:

  Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\bs4\element.py", line 1045, in __str__
    return self.encode()
  File "C:\Python27\lib\site-packages\bs4\element.py", line 1055, in encode
    u = self.decode(indent_level, encoding, formatter)
  File "C:\Python27\lib\site-packages\bs4\element.py", line 1126, in decode
    indent_contents, eventual_encoding, formatter)
  File "C:\Python27\lib\site-packages\bs4\element.py", line 1195, in decode_contents
    formatter))
  File "C:\Python27\lib\site-packages\bs4\element.py", line 1126, in decode
  ......
  
  File "C:\Python27\lib\site-packages\bs4\element.py", line 1126, in decode
    indent_contents, eventual_encoding, formatter)
  File "C:\Python27\lib\site-packages\bs4\element.py", line 1195, in decode_contents
    formatter))
  File "C:\Python27\lib\site-packages\bs4\element.py", line 1098, in decode
    text = self.format_string(val, formatter)
  File "C:\Python27\lib\site-packages\bs4\element.py", line 163, in format_string
    output = formatter(s)
  File "C:\Python27\lib\site-packages\bs4\element.py", line 120, in substitute_xml
    ns, EntitySubstitution.substitute_xml)
  File "C:\Python27\lib\site-packages\bs4\element.py", line 104, in _substitute_if_appropriate
    if (isinstance(ns, NavigableString)
RuntimeError: maximum recursion depth exceeded while calling a Python object

  而后更神奇的是我使用的ptpython并没有报错,直接通过了。

  其实原因是在Python里的递归调用是有限制的,可以使用sys模块里的getrecursionlimit方法查看的到,即(想深入的同学可以谷歌上搜索一番,这里提供笔者所搜索到的https://cyrusin.github.io/2015/12/08/python-20151208/

sys.getrecursionlimit()

打开终端运行Python,可以看到默认限制值为1000

技术分享

而ptpython里默认限制值为2000,这也不难解释为什么python下直接运行会报最大深度递归错误而ptpython可以正常运行了。

技术分享

  那么该来解决这个问题了,有get自然有set(当然还有其他方法比如达到深度限制时就做对应处理这方面不符合笔者目前需求,所以就不赘述,有需求的同学请自行谷歌百度一下),那么设置最大深度限制的方法就是setrecursionlimit了,至于设置值为多少你自行设置了

sys.setrecursionlimit(2000)

至此,问题解决!


本文出自 “云驿站 -Leyex学习笔记” 博客,请务必保留此出处http://leyex.blog.51cto.com/4230949/1884041

文章来自:http://leyex.blog.51cto.com/4230949/1884041
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3