user6139904
user6139904

Reputation:

Can I change background/text colour during a program in python?

I am looking to either change the colour of background shell or the text during while the program is running. I am aware I can change the themes in the options to do this permanently but that is not what I am looking for. Is it possible to do this or not?

Upvotes: 2

Views: 5666

Answers (3)

José Nunes
José Nunes

Reputation: 64

I would suggest colorama library:

https://pypi.python.org/pypi/colorama

Example:

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')

Upvotes: 2

zondo
zondo

Reputation: 20336

Yes it is. It might not work in all terminals, but there are escape sequences for this:

print("\033[34;42mMy text\033[m")

will print My text in blue on a background of green.

The escape sequence is \033[ followed by ;-separated numbers, followed by m. To end the color, you use \033[m. The numbers are 1 to make the text bold, 3 with another number to make the text the color of the other number, and 4 with another number to make the text background the color of the other number. The other numbers mentioned for 3 and 4 are the following:

0 -> Black
1 -> Red
2 -> Green
3 -> Yellow
4 -> Blue
5 -> Purple
6 -> Cyan
7 -> Light Gray

Upvotes: 3

alec_djinn
alec_djinn

Reputation: 10789

It is possible even if it is not that straight forward. Fortunately, there is a nice library called colorama that can help you out with this. Check it out here http://pypi.python.org/pypi/colorama

Without using extra libraries, you have to use ANSI escape chars, http://ozzmaker.com/add-colour-to-text-in-python/

Upvotes: 1

Related Questions