pythoncolorama

SlowPrint with colors


I have an issue. I'm not able to use the slowprint function at the same time as colorama or other color modules.

Here's my code:

import os, sys
import time
import colorama
from colorama import init, Fore, Back, Style
colorama.init(autoreset=True)

#SlowPrint 
def print_slow(str):
    for letter in str:
        sys.stdout.write(letter)
        sys.stdout.flush()
        time.sleep(0.01)
#Test
print_slow (f"{Fore.RED}Hello World")

The output is:

←[31mHellow World

Instead of the actual color getting applied. How do I fix this?


Solution

  • Your code is doing print_slow(f"{Fore.RED}Hello World"). But what you are doing in print_slow() appears to be affecting the way your console driver handles the VT100 emulation that acts on the control codes for the colours. Understand that when you see ←[31m, that is what is actually being sent to the console. The codes only make colours because of a decades-old convention introduced by DEC dumb terminals. They only work with terminal drivers. Don't expect to see the colours in an IDE, or if you pipe the output to a file and open it in Notepad.

    So, don't call print_slow() on the control codes. Instead, do print(Fore.RED, end="") and only after that print_slow ("Hello World"). But if you do that, you also have to change

    colorama.init(autoreset=True)
    

    to

    colorama.init(autoreset=False)
    

    because if you set autoreset=True, that unsets the colours after every call to print(). But if you change autoreset, you may also have to do print(Style.RESET_ALL, end="") to explicitly unset the colours. Whether you need that depends on what else your program is doing.

    This will fix the problem:

    import os
    import sys
    import time
    import colorama
    from colorama import init, Fore, Back, Style
    colorama.init(autoreset=False)
    
    
    def print_slow(str):
        for letter in str:
            sys.stdout.write(letter)
            sys.stdout.flush()
            time.sleep(0.01)
    
    if __name__ == '__main__':
        print(Fore.RED, end="")
        print_slow("Hello World")
        print(Style.RESET_ALL, end="")