45

I'm looking for a way to change the color of the text output from my python scripts as it runs. The basic idea is something like this:

if (Data < LowerLimit):
    print "Failed" # Output Failed as Red Text
elif (Data > UpperLimit):
    print "Failed" # Red Color
else:
    print "Passed" # Blue Color

The scripts are being used on windows machines for quick data analysis.

martineau
  • 119,623
  • 25
  • 170
  • 301
CyanRook
  • 8,664
  • 4
  • 21
  • 20

2 Answers2

73

Or about the best module I have found http://pypi.python.org/pypi/colorama

Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91
  • 2
    Yes - colorama actually works for the Windows 7 command prompt. Prior to windows 10, the ANSI codes don't work (for some inscrutable reason) in the command prompt. Colorama can use Win32 commands entirely transparantly - which makes it work and makes it easy to use. I'm glad I finally found a solution to this problem. – Noise in the street Apr 26 '17 at 11:25
  • @Noiseinthestreet Can you this this => https://stackoverflow.com/a/70599663/3057246 – Vinod Srivastav Jan 18 '22 at 08:39
15

This is extremely simple! Rather than importing odd modules for python or trying long commands you can take advantage of windows OS commands.

In windows, commands exist to change the command prompt text color. You can use this in python by starting with a: import os

Next you need to have a line changing the text color, place it were you want in your code. os.system('color 4')

You can figure out the other colors by starting cmd.exe and typing color help.

The good part? Thats all their is to it, to simple lines of code. -Day

Daymarquez
  • 329
  • 2
  • 3
  • 27
    That changes the colour of the whole console, not just the text printed afterwards. – zvone Mar 03 '13 at 03:57
  • Sorry about that guys. I was sleepy and totally misunderstood the question. – Daymarquez Jul 10 '15 at 21:14
  • It's still a valid answer to the EXTREMELY RELATED question LIKELY TO GET MARKED DUPLICATE which is how to change shell text color in Python... – Ian Oct 26 '16 at 17:30
  • Upvoted, because while it might not exactly answer the original question, this does answer my question for which Google brought me here. – szmate1618 Dec 08 '18 at 12:41
  • 15
    Actually, if you run os.system('color'), then the ANSI escape sequences magically start working in windows. – Szabolcs Dec 12 '18 at 16:48
  • See here to print colorful text on any console without any fancy modules (simple and easy) https://stackoverflow.com/a/72752520/18522747 – Abhijeet Jul 29 '22 at 21:33
  • did not work. I think zvone might be right. – Spero May 06 '23 at 11:31