pythonpython-3.xlinuxtput

Python3 + How to change the output color when using print command


as maybe some of you know and regarding to shell scripts - tput is utility uses the terminfo database to make the values of terminal-dependent capabilities and information available to the shell

in my python script I have the following example: ( just a sample from long code )

for TOPIC in list:
  if str(val) in TOPIC:
     word = TOPIC.split()[1]
     print ("Topic " + word + " is successfully configured")
  else:
      try:
       word = TOPIC.split()[1]
       print ("Topic " + word + " bad configuration")
      except IndexError:
       pass

I want to change the color from white to green on the following printing:

 print ("Topic " + word + " is successfully configured")

or to change the color from white to red on:

print ("Topic " + word + " bad configuration")

is it possible to change the color in python3 as we did for example in bash scripts?


Solution

  • import os
    os.system("")
    
    RED = "\x1B["
    GREEN = '\033[32m'
    
    word = "random_topic_name"
    print(GREEN+"Topic " + word + "successfully configured" )
    print(RED+"Topic " + word + "bad configuration" )