gpt4 book ai didi

python - 致命的Python错误: Cannot recover from stack overflow

转载 作者:行者123 更新时间:2023-12-02 03:31:00 26 4
gpt4 key购买 nike

我在互联网上读到类似的问题,但没有一个答案可以帮助我。我有一个函数,对于每一行数据(数据大约有 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

None

--------------------------------------------------------------------------- RecursionError Traceback (most recent call last) in () 8 9 print(test_(0,2971)) ---> 10 print(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))

... last 1 frames repeated, from the frame below ...

in test_(x, t) 5 x = x+1 6 if x 7 test_(x=x,t=t) 8 9 print(test_(0,2971))

RecursionError: maximum recursion depth exceeded in comparison

为了克服这个问题,我在不失去“运行连续性”的情况下调整了该函数,以便我可以使用批处理:

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

有人有更好的解决方案吗?另外,一般来说,当我们知道有很多迭代要做时,执行递归函数是一个坏主意?还有人知道如何在每个循环中打印递归深度吗?

我正在 Linux 虚拟环境上工作,使用 jupyter 笔记本,在 python 3.6 上使用 anaconda。

最佳答案

请检查这个问题(它对我有用): 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

关于python - 致命的Python错误: Cannot recover from stack overflow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50508591/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com