How to print colour/color in python?
Solution 1:
If you want to print color in the IDLE shell no answer using ASCI escape codes will help you as it does not implement this feature.
There is a hack specific to IDLE that lets you write to it's PyShell
object directly and specify text tags that IDLE has already defined such as "STRING"
which will appear as green by default.
import sys
try:
shell = sys.stdout.shell
except AttributeError:
raise RuntimeError("you must run this program in IDLE")
shell.write("Wanna go explore? ","KEYWORD")
shell.write("OPTIONS","STRING")
shell.write(" : ","KEYWORD")
shell.write("Yes","DEFINITION")
shell.write(" or ","KEYWORD")
shell.write("No","COMMENT")
answer = input()
When run in IDLE will result in this prompt:
Here is a list of all valid tags for use:
print("here are all the valid tags:\n")
valid_tags = ('SYNC', 'stdin', 'BUILTIN', 'STRING', 'console', 'COMMENT', 'stdout',
'TODO','stderr', 'hit', 'DEFINITION', 'KEYWORD', 'ERROR', 'sel')
for tag in valid_tags:
shell.write(tag+"\n",tag)
Note that 'sel'
is special that it represents the text that is selected, so it will be un-selected once something else is clicked on. As well it can be used to start some text selected for copying.
Solution 2:
If you just want a really simply and straightforward way to print ansi colors in the terminal you can check out the ansicolor package module:
Install via pip
$ pip install ansicolors
Usage snippet
from colors import red, green, blue
print red('This is red')
print green('This is green')
print blue('This is blue')
from colors import color
for i in range(256):
print color('Color #%d' % i, fg=i)
Note about pip
pip is a python package manager. If you don't have pip
installed, you can install it with easy_install pip
If you then find you don't have easy_install
, then download this: http://peak.telecommunity.com/dist/ez_setup.py and do:
python ez_setup.py
easy_install pip
Colors for windows command shell
The above ansi colors will not work for you in a windows command shell. Try looking at this activestate code snippet