5

I'm trying to use colored output using python

1- I tried to use this format :

print '\033[1;30mGray like Ghost\033[1;m'

I got this output :

←[1;30mGray like Ghost←[1;m

2- I tried to use termcolor package as :

from termcolor import colored, cprint
text = colored('Hello, World!', 'red', attrs=['reverse', 'blink'])
print(text)

I got this output :

[5m[7m[31mHello, World![0m

Why I can't use colors with the output?

I tried other ways and all give almost the same output Is there another way I can try?

Raghad Qu
  • 51
  • 1
  • 3
  • 2
    Because I'm pretty sure it depends on the console/editor, not the code itself, if it will support colored output or not. – Roko Nov 27 '18 at 10:17
  • 1
    I tried on Python (command line ) python.exe also with the same reults – Raghad Qu Nov 27 '18 at 10:20
  • I guess that [this post](https://stackoverflow.com/questions/287871/how-to-print-colored-text-to-the-terminal) can help you understanding. They say that it depends surely on the console as Roko said you're using, and on the OS you're executing your python code. – Marte Valerio Falcone Aug 07 '21 at 11:26

3 Answers3

3

I know you only mentioned Colorama in a comment on Tom Dee's answer rather than in your original question, but I had the same issue with Colorama until I added this code which initializes Colorama before trying to print colored text:

from colorama import init
init()
Cody Mayers
  • 355
  • 6
  • 19
2

I was having the same issue until I imported logging and coloredlogs

from termcolor import colored
import logging, coloredlogs
logger = logging.getLogger(f"Logger")
coloredlogs.install(logger=logger)

It fixed my issue.

MD Mushfirat Mohaimin
  • 1,966
  • 3
  • 10
  • 22
Zakir Ayub
  • 105
  • 8
0

Since you commented that you were using python.exe I take it you have only tried in windows. Windows cmd doesn't support ANSI coding like linux/unix which termcolor uses. Therefore you'll have to use another package to do this. I would suggest looking into colorama (https://pypi.org/project/colorama/).

from colorama import Fore, Back, Style
print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')

This example from the website shows you how to change the foreground and background to several colours.

Tom Dee
  • 2,516
  • 4
  • 17
  • 25
  • I tried this one and it's not working with me For example this is the output of the first print you wrote :←[31msome red text – Raghad Qu Nov 28 '18 at 14:47