简体   繁体   中英

Getting error “Maximum recursion depth exceeded while calling a Python object”

So I just received an error that I kinda don't understand what is the reason of.

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])

As I can see it has something with the logger that I have created myself that looks like:

Utils class

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()

And basically I made also a simple code of how my code looks like as well:

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

So the problem is that after a while it gives me an error of maximum recursion depth exceeded while calling a Python object but I only get it whenever I print out except Exception as err: but when I see through a console it gives me the output that is given at the top.

The question is now that I have actually no idea what the cause of it is.

Edit

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()

As I understood from the discussion in the comments to the question, you may create multiple instances of the Logger class during the execution of your script. Each creation of a Logger invokes colorama.init() . Each call to colorama.init() forces Colorama to replace sys.stdout and sys.stderr streams with colorama-wrapped versions of them.

After more and more calls to colorama.init your streams turn into fat onions of lots of (uselessly repeated) colorama wrapper layers, and a single call to print has to get passed recursively from layer to layer until it reaches the actual sys.stdout .

When the number of layers exceeds the maximum allowed stack depth, you get your exception. This situation is also referenced in this open colorama issue .

The easiest way to fix the problem would be to move colorama.init() out of the Logger constructor, and have something like that globally instead:

import colorama
colorama.init()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM