运行时错误:超过最大递归深度
我有一段代码,它通过匹配不同的模式从文本中提取两个字符串。
def urlChange(self, event):
text = self.txtUrl.GetValue()
matches = re.findall('GET (\S+).*Host: (\S+).*Cookie: (.+\S)\s*', text, re.DOTALL or re.MULTILINE)
if matches:
groups = matches[0]
self.txtUrl.SetValue(groups[1] + groups[0])
self.txtCookie.SetValue(groups[2])
else:
matches = re.findall('GET (\S+).*Host: (\S+).*', text, re.DOTALL or re.MULTILINE)
if matches:
groups = matches[0]
self.txtUrl.SetValue(groups[1] + groups[0])
self.txtCookie.Clear()
else:
matches = re.findall('.*(http://\S+)', text, re.DOTALL or re.MULTILINE)
if matches:
self.txtUrl.SetValue(matches[0])
matches = re.findall('.*Cookie: (.+\S)', text, re.DOTALL or re.MULTILINE)
if matches:
self.txtCookie.SetValue(matches[0])
只有当最后一条 re.findall('.*(http://\S+)'...
语句运行时,我才会收到以下错误信息:
Traceback (most recent call last):
File "./curl-gui.py", line 105, in urlChange
text = self.txtUrl.GetValue()
RuntimeError: maximum recursion depth exceeded
Error in sys.excepthook:
Traceback (most recent call last):
File "/usr/lib/python2.6/dist-packages/apport_python_hook.py", line 48, in apport_excepthook
if not enabled():
File "/usr/lib/python2.6/dist-packages/apport_python_hook.py", line 21, in enabled
import re
RuntimeError: maximum recursion depth exceeded while calling a Python object
Original exception was:
Traceback (most recent call last):
File "./curl-gui.py", line 105, in urlChange
text = self.txtUrl.GetValue()
RuntimeError: maximum recursion depth exceeded
2 个回答
1
你有没有试过用 sys.setrecursionlimit() 来提高递归的限制?默认情况下,这个限制是1000。
2
这看起来像是图形用户界面(GUI)的代码?
如果是这样的话,我猜当 self.txtUrl
发生变化时,urlChange
就会被调用。因此,当你执行 self.txtUrl.SetValue(matches[0])
时,它又会触发一次 urlChange
的调用,这样就会不断重复,最终达到递归的限制。
这只是我的猜测——需要更多的上下文才能确认,但在这段代码中,我能看到的唯一可能的递归行为就是这个。
为了避免这个问题,你应该在调用 SetValue
之前检查一下 textUrl
的值,看看它是否真的发生了变化,以防止递归的发生。