致命的Python错误: 无法从s中恢复

2024-04-29 14:59:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我在网上看到类似的问题,但没有一个答案能帮到我。我有一个函数,对每一行数据(数据大约有2000'000行)执行一些操作,然后根据所做的操作调用具有不同参数的同一个函数。问题是,过了一段时间,我在终端中得到这个错误:“致命的Python错误:无法从堆栈溢出中恢复。”

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

首先,我不明白“致命的Python错误:无法从堆栈溢出中恢复”和jupyternotebook中的“recursion error:maximum recursion depth exceeded in comparison”之间的区别。实际上,对我来说,它可能来自同一个错误(例如无限循环)。

当用一个名为“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笔记本,使用Python3.6。


Tags: 数据函数intestif堆栈错误sys
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

我的问题是在连接不好的情况下向某个API发送请求。它是一个使用bot.polling()方法的库,因此可能请求溢出或其他原因。

相关问题 更多 >