You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

是否存在getrecursiondepth()函数?如何获取Python脚本当前递归深度?

Python获取当前递归深度的正确方法

首先明确:Python标准库中不存在sys.getrecursiondepth()函数,不管是sys模块还是其他内置模块都没有这个方法,你遇到的报错正是因为它根本不存在。

下面提供两种可靠的方法获取当前递归深度:

方法1:利用traceback模块读取调用栈

调用栈的长度对应递归层级,我们可以通过traceback.extract_stack()获取当前栈帧列表,列表长度减去固定偏移量(抵消traceback自身调用的栈帧)就是当前递归深度:

import traceback
import sys

def recursion_depth():
    # 减去2是排除traceback.extract_stack()和当前函数调用的额外栈帧
    current_depth = len(traceback.extract_stack()) - 2
    with open("recursion_depth.txt", "a") as f:
        f.write(f"递归深度: {current_depth}\n")
    # 留一个余量防止触发递归限制报错
    if current_depth < sys.getrecursionlimit() - 1:
        recursion_depth()

recursion_depth()

方法2:手动维护深度参数(更高效)

直接在递归函数的参数中添加一个深度变量,每次递归调用时递增,这种方式不需要额外模块,性能更优:

import sys

def recursion_depth(current_depth=1):
    with open("recursion_depth.txt", "a") as f:
        f.write(f"递归深度: {current_depth}\n")
    # 递归终止条件,留余量避免栈溢出
    if current_depth < sys.getrecursionlimit() - 1:
        recursion_depth(current_depth + 1)

recursion_depth()

另外需要修正你提供的原代码问题:原代码中if depth < sys.getrecursionlimit()里的depth未定义,且使用了不存在的sys.getrecursiondepth(),上面的示例已经修复了这些问题。

内容的提问来源于stack exchange,提问作者donaldekpe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 00:52:44