收到错误“调用Python对象时超出了最大递归深度”

时间:2018-11-24 23:11:12

标签: python python-3.x error-handling runtime-error

所以我刚收到一个错误,我有点不明白是什么原因。

Traceback (most recent call last):
  File "C:\Users\utils.py", line 657, in script
    logger.warn('Wopsiy! No word found!')
  File "C:\Users\utils.py", line 30, in warn
    sys.stdout.write("{}{} {}".format(self.__timestamp(), '[' + self.name + '] -', colored(text, "yellow")))
  File "C:\Program Files\Python36\lib\site-packages\colorama\ansitowin32.py", line 40, in write
    self.__convertor.write(text)
  File "C:\Program Files\Python36\lib\site-packages\colorama\ansitowin32.py", line 141, in write
    self.write_and_convert(text)
  File "C:\Program Files\Python36\lib\site-packages\colorama\ansitowin32.py", line 166, in write_and_convert
    self.write_plain_text(text, cursor, start)
  File "C:\Program Files\Python36\lib\site-packages\colorama\ansitowin32.py", line 174, in write_plain_text
    self.wrapped.write(text[start:end])
  File "C:\Program Files\Python36\lib\site-packages\colorama\ansitowin32.py", line 40, in write
    self.__convertor.write(text)
  File "C:\Program Files\Python36\lib\site-packages\colorama\ansitowin32.py", line 141, in write
    self.write_and_convert(text)
  File "C:\Program Files\Python36\lib\site-packages\colorama\ansitowin32.py", line 169, in write_and_convert
    self.write_plain_text(text, cursor, len(text))
  File "C:\Program Files\Python36\lib\site-packages\colorama\ansitowin32.py", line 174, in write_plain_text
    self.wrapped.write(text[start:end])

正如我所见,它与我自己创建的记录器类似,

实用程序类

from datetime import datetime
from termcolor import cprint, colored
import sys

import colorama

class Logger:

    def __init__(self,name):
        colorama.init()
        self.name = name

    @staticmethod
    def __timestamp():
        timestamp = str(datetime.now().strftime("[%H:%M:%S.%f")[:-3]+"]")
        return timestamp

    def warn(self, text):
        sys.stdout.write("{}{} {}".format(self.__timestamp(), '[' + self.name + '] -', colored(text, "yellow")))
        sys.stdout.write("\n")
        sys.stdout.flush()

基本上,我还编写了一个简单的代码来说明代码的外观:

from utils import Logger
logger = Logger('Script')

def main():
    logger = Logger("product_info")
    word = ['Nope', 'There', 'Is', 'No', 'Word']
    while True:

        try:

            for _ in infinity():
                 if 'Hello' in word:
                     print('WORKS!!')

            else:
                logger.warn('Wopsiy! No word found!')
                time.sleep(1)

         except Exception as err:
              print(err)
              time.sleep(1)
              continue

所以问题是一段时间后,它给了我一个maximum recursion depth exceeded while calling a Python object的错误,但是我只有在打印出except Exception as err:时才得到它,但是当我通过控制台查看时,它给出的输出是在顶部给出。

现在的问题是,我实际上不知道是什么原因。

编辑

from datetime import datetime
from termcolor import cprint, colored
import sys

import colorama
colorama.init()
class Logger:

    def __init__(self,name):
        self.name = name

    @staticmethod
    def __timestamp():
        timestamp = str(datetime.now().strftime("[%H:%M:%S.%f")[:-3]+"]")
        return timestamp

    def warn(self, text):
        sys.stdout.write("{}{} {}".format(self.__timestamp(), '[' + self.name + '] -', colored(text, "yellow")))
        sys.stdout.write("\n")
        sys.stdout.flush()

1 个答案:

答案 0 :(得分:2)

从对问题的评论中的讨论中可以理解,您可以在脚本执行期间创建Logger类的多个实例。每次创建Logger都会调用colorama.init()。每次对colorama.init()的调用都会迫使Colorama用Colorama包装的版本替换sys.stdoutsys.stderr流。

在对colorama.init的调用越来越多之后,您的流变成了很多(无用重复)colorama包装层的胖洋葱,并且对print的单个调用必须逐层递归传递直到达到实际的sys.stdout

当层数超过允许的最大堆栈深度时,就会出现异常。 this open colorama issue中也提到了这种情况。

解决此问题的最简单方法是将colorama.init()移出Logger构造函数,并在全局范围内添加类似的内容:

import colorama
colorama.init()