Search code examples
pythonpython-3.xcolorscoloramawrds

How to generate a Python output file with color formatting?


How can I instruct python to generate an output file which keeps the color formatting specified in the main script?

I am working on the WRDS Cloud and I am using a shell file to execute a python script. The Cloud returns an output file which I can download and open like it is a txt file. However, this does not keep the color formatting that I specified in my original code.

I have tried to use different formatting packages in my python script but the result is always the same: the color is not displayed in the output file. I would really need to see the color because I use it to highlight some particular messages that represent warnings or errors. Therefore, I assume the only way around this is to instruct my python script to generate a different type of output, but I cannot figure out how.

my python script looks like this:

from colorama import *
init()
print(Fore.MAGENTA + 'Warning: The query failed' + Fore.RESET)

the output file looks like this (with no magenta color):

Warning: The query failed

Solution

  • The simple answer is that: "A simple text file cannot have different colors"

    Colorama (and all the others terminal-color-suites) put "special characters" before the text that you want to color. Those caracters are "read" by the terminal that will output the correct character and the correct color (and also delete the special character so that the final user will never know that).

    There is no way to color plain text because there is no one that "read" the special character and interpret them.

    Also a protip for the future, dont import the whole library with a *, select the module you're going to use and import them explicitly like this:

    from colorama import Fore
    print(Fore.RED + 'some red text' + Fore.RESET)