首页 文章

致命的Python错误:无法从堆栈溢出中恢复

提问于
浏览
2

我在互联网上阅读类似的问题,但没有一个答案可以帮助我 . 我有一个函数,对于每行数据(数据有大约2'000'000行)做某事,然后根据它做了什么,用不同的参数调用相同的函数 . 问题是,经过一段时间后,我在终端中收到此错误:'致命的Python错误:无法从堆栈溢出中恢复 .

它会导致导致此错误的最常见错误是无限循环,但我控制并且没有无限循环 . 因此,对我来说问题'sys.getrecursionlimit()'设置为3000,这意味着在3000调用相同的函数后它会给我错误 .

首先,我不明白'致命的Python错误:无法从堆栈溢出中恢复'之间的区别 . 在终端中,或jupyternotebook中的'RecursionError:超出比较的最大递归深度' . 实际上,对我而言,它可能来自同样的错误(例如无限循环) .

当用一个名为'test_'的简单函数替换我的函数时,我有以下代码:

import sys
print(sys.getrecursionlimit())

def test_(x,t):
    x = x+1
    if x<t:
        test_(x=x,t=t)

print(test_(0,2971)) # output: None
print(test_(0,2972)) # RecursionError: maximum recursion depth exceeded in comparison

3000无----------------------------------------------- ---------------------------- RecursionError Traceback(最近一次调用last)in()8 9 print(test_(0,2971)) ---> 10打印(test_(0,2972))in test_(x,t)5 x = x 1 6 if x 7 test_(x = x,t = t)8 9 print(test_(0,2971) )...最后1帧重复,从下面的帧...在test_(x,t)5 x = x 1 6如果x 7 test_(x = x,t = t)8 9打印(test_(0, 2971))RecursionError:比较时超出了最大递归深度

为了克服这个问题,我调整了函数而没有失去“运行的连续性”,因此我可以使用批次:

for i in np.arange(0,9000,2000):
    test_(i,i+2000)

有人会有更好的解决方案吗?另外,一般来说,当我们知道要进行大量迭代时,做递归函数是个坏主意吗?也有人知道我怎么能在每个循环打印recursiondeepth?

我正在研究一个Linux虚拟环境,使用jupyter笔记本,在python 3.6上使用anaconda .

1 回答

  • 2

    请检查这个问题(这对我有用):How do I get the current depth of the Python interpreter stack?

    您的代码基于该答案:

    import sys
    import inspect
    print(sys.getrecursionlimit())
    
    def test_(x,t):
        print len(inspect.stack())
        x = x+1
        if x<t:
            test_(x=x,t=t)
    
    print(test_(0,7))
    

    输出:

    22
    23
    24
    25
    26
    27
    28
    None
    

相关问题