3

i'm new to python (about a week or less) and I'm using python 2.7.

i'm writing a program to check ip validation and classes and i want to make the output in color, so it will be more readable on terminal to the user.

i have already tried this:

# to make the text purple for example.
print '\033[95m' + "This is a purple output"
# if i'm writing another simple print after the first one it will be purple too
print "Example" # now this statement purple too

but when i use this example the output after the first print method become purple too.

Thank for everyone who try.

shemesh
  • 51
  • 1
  • 8

2 Answers2

3

By printing escape code \033[0m, you can reset the color:

>>> print '\033[95m' + "This is a purple output" + '\033[0m'
This is a purple output

Alternatively, you can use colorama package:

>>> from colorama import Fore
>>> print Fore.LIGHTMAGENTA_EX + "This is a purple output" + Fore.RESET
This is a purple output
falsetru
  • 357,413
  • 63
  • 732
  • 636
1

well i think this is the best way i could think of.

class FontColors:
    def __init__(self):
        self.PURP = '\033[95m'
        self.LIGHTBLUE = '\033[94m'
        self.ENDC = '\033[0m'
        self.UNDERLINE = '\033[4m'
        self.LIGHTYELL = '\033[92m'
        self.BYELL = '\033[93m'
        self.FRED = '\033[91m'
        self.BOLD = '\033[1m'

color = FontColors()

# you can try like this - **the color.ENDC meant to make the output normal again.**
print "{0}This is a Purple output{1}".format(color.PURP, color.ENDC)
# or like this
print color.BYELL + "This is a Yellow output" + color.ENDC

Thank you @falsetru for helping me with this problem.

shemesh
  • 51
  • 1
  • 8