/ 前言 /
不久前寫了一個腳本檢測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