2

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()
12
  • Looks like an instance of this issue: github.com/tartley/colorama/issues/140 Commented Nov 24, 2018 at 23:28
  • If I understand it correctly, the issue may happen when you call colorama.init() several times. Try moving this invocation out of the Logger constructor into the global scope. Commented Nov 24, 2018 at 23:33
  • @KT.You might be very right, Do you have any example how moving out form Logger into a global would help? Commented Nov 24, 2018 at 23:33
  • Just put colorama.init right after import colorama. As far as I understand this init call wraps global streams with colorama filters, and when you re-wrap them again (by calling colorama.init multiple times) things just get worse. Commented Nov 24, 2018 at 23:35
  • For example, the line "for i in range(1000): colorama.init()" manages to crash the interpreter for me. Commented Nov 24, 2018 at 23:36

1 Answer 1

3

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()
Sign up to request clarification or add additional context in comments.

2 Comments

This seem to be the actually issue and I will try give it a go and give it few hours! I will come back if no issues comes up!
Seems to work! Tried it for 2 days and not a single error!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.