6

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?

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. Commented Nov 27, 2018 at 10:17
  • 1
    I tried on Python (command line ) python.exe also with the same reults Commented Nov 27, 2018 at 10:20
  • I guess that this post 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. Commented Aug 7, 2021 at 11:26

3 Answers 3

5

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()
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

1

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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.