如何获得Python解释器堆栈的当前深度? [英] How do I get the current depth of the Python interpreter stack?

查看:212
本文介绍了如何获得Python解释器堆栈的当前深度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档:

sys.getrecursionlimit()

返回递归限制的当前值,即Python解释器堆栈的最大深度.此限制可防止无限递归 导致C堆栈溢出和Python崩溃的原因.有可能 由setrecursionlimit()设置.

Return the current value of the recursion limit, the maximum depth of the Python interpreter stack. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. It can be set by setrecursionlimit().

我当前在腌制对象时达到了递归限制.我腌制的对象只有几个层次的嵌套,所以我对正在发生的事情感到有些困惑.

I am currently hitting the recursion limit when pickling an object. The object I am pickling only has a few levels of nesting, so I am a bit puzzled by what is happening.

我可以通过以下黑客措施来解决此问题:

I have been able to circumvent the issue with the following hack:

try:
    return pickle.dumps(x)
except:
    try:
        recursionlimit = getrecursionlimit()
        setrecursionlimit(2*recursionlimit)
        dumped = pickle.dumps(x)
        setrecursionlimit(recursionlimit)
        return dumped
    except:
        raise

在不同的上下文中测试以上代码片段有时会在第一个try上获得成功,有时会导致在第二个try上获得成功.到目前为止,我还没有使其成为raise例外.

Testing the above snippet on different contexts sometimes leads to success on the first try, and sometimes it leads to success on the second try. So far I have not been able to make it raise the exception.

要进一步调试我的问题,有一种获取当前堆栈深度的方法将很有帮助.这将使我能够验证输入的堆栈深度是否正在确定上面的代码段将在第一个try还是第二个成功.

To further debug my issue it would be helpful to have a way to obtain the current depth of the stack. That would allow me to verify if the entering stack depth is determining whether the snippet above will succeed on the first try or on the second.

标准库是否提供获取堆栈深度的功能,否则,如何获取堆栈的深度?

Does the standard library provide a function to get the depth of the stack, or if not, how can I obtain it?

def get_stack_depth():
    # what goes here?

推荐答案

您可以从inspect.stack()看到整个调用堆栈,因此当前使用的深度将是len(inspect.stack(0)).

You can see the whole call stack from inspect.stack(), so currently taken depth would be len(inspect.stack(0)).

另一方面,我想当出现超出最大递归深度" 异常时,您可以打印出完整的堆栈.该堆栈跟踪应该向您确切显示出了什么问题.

On the other hand, I guess you got the complete stack printed out when "maximum recursion depth exceeded" exception was raised. That stack trace should show you exactly what went wrong.

这篇关于如何获得Python解释器堆栈的当前深度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆