解决RuntimeError: maximum recursion depth exceeded递归异常

/ 前言 /

       不久前写了一个脚本检测Linux某一个服务是否是启动状态, 因为服务启动时间较长就加了一个递归操作, 结果报错RuntimeError: maximum recursion depth exceeded, 我们来看下如何解决

/ 1 / 问题分析

       问题出现后我去网上查找发现报错原因是递归次数超过了Python3.x的默认递归深度, 那么我们来测试一下Python3.x和Python2.x的递归深度是多少

测试代码
# -*- coding: UTF-8 -*-

def recursion_test (num):
	print("当前递归次数 : {%s}"%num)
    num += 1
    recursion_test(num)

if __name__ == '__main__':
    recursion_test(1)
Python3.7测试结果

在递归997次时报错

/usr/bin/python /Users/wise/projects/one-box/python/test.py
当前递归次数 : {1}
...
当前递归次数 : {997}
Traceback (most recent call last):
  File "/Users/wise/projects/one-box/python/test.py", line 10, in <module>
    recursion_test(1)
  File "/Users/wise/projects/one-box/python/test.py", line 6, in recursion_test
    print("当前递归次数 : {%s}"%num)
RuntimeError: maximum recursion depth exceeded while getting the str of an object

Process finished with exit code 1
Python2.7测试结果

在递归999次时报错

/usr/bin/python /Users/wise/projects/one-box/python/test.py
当前递归次数 : {1}
...
当前递归次数 : {999}
Traceback (most recent call last):
  File "/Users/wise/projects/one-box/python/test.py", line 10, in <module>
    recursion_test(1)
  File "/Users/wise/projects/one-box/python/test.py", line 6, in recursion_test
    print("当前递归次数 : {%s}"%num)
RuntimeError: maximum recursion depth exceeded while getting the str of an object

Process finished with exit code 1

/ 2 / 解决方法

修改Python默认递归次数

import sys
sys.setrecursionlimit(2000)

测试结果

当前递归次数 : {1}
...
当前递归次数 : {1998}
Traceback (most recent call last):
  File "/Users/wise/PycharmProjects/csdn/test.py", line 10, in recursion_test
  [Previous line repeated 996 more times]
  File "/Users/wise/PycharmProjects/csdn/test.py", line 8, in recursion_test
    print("当前递归次数 : {%s}"%num)
RecursionError: maximum recursion depth exceeded while calling a Python object

你可能感兴趣的:(Python)