views:

17368

answers:

14

I want to print in the terminal with colors ? how can I do that in python ?

Another questions what is the best character that when it is printed it look like a box [brick] ?

I want to print colored blocks, it is part of game :)

+4  A: 

For windows you cannot print to console with colors unless your using the win32api.

For linux its as simple as using print, with the escape sequences outlined here:

Colors

For the characther to print like a box, it really depends on what font you are using for the console window. The pound symbol works well, but it depends on the font:

#
UberJumper
+6  A: 

You can use the Python implementation of the curses library: http://docs.python.org/library/curses.html

Also, run this and you'll find your box:

for i in range(255):
    print i, chr(i)
daharon
Doesn't work on Windows.
Sorin Sbarnea
+5  A: 

You want to learn about ANSI escape sequences. Here's a brief example:

CSI="\x1B["
reset=CSI+"m"
print CSI+"31;40m" + "Colored Text" + CSI + "0m"

For more info see http://en.wikipedia.org/wiki/ANSI_escape_code

For a block character, try a unicode character like \u2588:

print u"\u2588"

Putting it all together:

print CSI+"31;40m" + u"\u2588" + CSI + "0m"
Bryan Oakley
+38  A: 

This somewhat depends on what platform you are on. The most common way to do this is by printing ANSI escape sequences. For a simple example, here's some python code from the blender build scripts:

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'

    def disable(self):
        self.HEADER = ''
        self.OKBLUE = ''
        self.OKGREEN = ''
        self.WARNING = ''
        self.FAIL = ''
        self.ENDC = ''

To use code like this, you can do something like

print bcolors.WARNING + "Warning: No active frommets remain. Continue?" 
      + bcolors.ENDC

This will work on unix, linux including macOS, and window (provided you enable ansi.sys). There are ansi codes for setting the color, moving the cursor, and more.

If you are going to get complicated with this (and it sounds like you are if you are writing a game), you should look into the "curses" module, which handles a lot of the complicated parts of this for you. The Python Curses HowTO is a good introduction.

If you are not using extended ASCII (i.e. not on a PC), you are stuck with the ascii characters below 127, and '#' or '@' is probably your best bet for a block. If you can ensure your terminal is using a IBM extended ascii character set, you have many more options. Characters 176, 177, 178 and 219 are the "block characters".

Some modern text-based programs, such as "Dwarf Fortress", emulate text mode in a graphical mode, and use images of the classic PC font. You can find some of these bitmaps that you can use on the Dwarf Fortress Wiki see (user-made tilesets).

The Text Mode Demo Contest has more resources for doing graphics in text mode.

Hmm.. I think got a little carried away on this answer. I am in the midst of planning an epic text-based adventure game, though. Good luck with your colored text!

what's the `disabled` used for?
Cawas
@Cawas It looks to me like it is for disabling coloring for all colors which are printed using a particular `bcolors` instance. For example, you could create a `bcolors` instance and then use the member variables of the instance to print out your coloring characters, but then if you decided you no longer wanted coloring, you could call `disable` before printing out the characters and they would just print out as empty strings.
Steven Oxley
Thanks @Steven I think I could picture an example in which we could use it.
Cawas
+3  A: 

If you are programming a game you may would like to change the background color and use spaces only :)

you may try something like

print " "+ "\033[01;41m" + " " +"\033[01;46m" + " " + "\033[01;42m"

suhib-alsisan
+1  A: 

For the characters

Your terminal most probably uses Unicode (typically UTF-8 encoded) characters, so it's only a matter of the appropriate font selection to see your favorite character. Unicode char U+2588, "Full block" is the one I would suggest you use.

Try the following:

import unicodedata
fp= open("character_list", "w")
for index in xrange(65536):
    char= unichr(index)
    try: its_name= unicodedata.name(char)
    except ValueError: its_name= "N/A"
    fp.write("%05d %04x %s %s\n" % (index, index, char.encode("UTF-8"), its_name)
fp.close()

Examine the file later with your favourite viewer.

For the colors

curses is the module you want to use. Check this tutorial.

ΤΖΩΤΖΙΟΥ
+5  A: 

On Windows you can use module 'win32console' (available in some Python distributions) or module 'ctypes' (Python 2.5 and up) to access the Win32 API.

To see complete code that supports both ways, see the color console reporting code from Testoob.

ctypes example:

import ctypes

# Constants from the Windows API
STD_OUTPUT_HANDLE = -11
FOREGROUND_RED    = 0x0004 # text color contains red.

def get_csbi_attributes(handle):
    # Based on IPython's winconsole.py, written by Alexander Belchenko
    import struct
    csbi = ctypes.create_string_buffer(22)
    res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi)
    assert res

    (bufx, bufy, curx, cury, wattr,
    left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
    return wattr


handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
reset = get_csbi_attributes(handle)

ctypes.windll.kernel32.SetConsoleTextAttribute(handle, FOREGROUND_RED)
print "Cherry on top"
ctypes.windll.kernel32.SetConsoleTextAttribute(handle, reset)
orip
ctypes was the key for me - on Windows.. Thx.
stiank81
A: 

There's also a module called WConIO that does much the same thing. Unfortunately the author will probably not be able to build a Python 2.6 version any time soon.

Tofystedeth
+20  A: 

I'm surprised no one has mentioned the Python termcolor module. Usage is pretty simple:

from termcolor import colored

print colored('hello', 'red'), colored('world', 'green')

It may not be sophisticated enough, however, for game programming and the "colored blocks" that you want to do...

Samat Jain
Does this work on Windows?
molasses
I didn't know about this before, thanks a lot!
Justin Poliey
Just a remark: its license is GPL and this may not be suitable for lots of Python projects including open-source ones. Also it just do not work under Windows.
Sorin Sbarnea
Yeah - doesn't work on Windows...
stiank81
+1  A: 

How about this

dugres
how about stopping spaming?
SilentGhost
What do you mean "spaming" ? What's wrong with this recipe ?
dugres
Louis? long time no see.
SilentGhost
That's not helping.
dugres
it's just to show louis why it is spamming.
SilentGhost
+3  A: 

Here's a curses example:

import curses

def main(stdscr):
    stdscr.clear()
    if curses.has_colors():
        for i in xrange(1, curses.COLORS):
            curses.init_pair(i, i, curses.COLOR_BLACK)
            stdscr.addstr("COLOR %d! " % i, curses.color_pair(i))
            stdscr.addstr("BOLD! ", curses.color_pair(i) | curses.A_BOLD)
            stdscr.addstr("STANDOUT! ", curses.color_pair(i) | curses.A_STANDOUT)
            stdscr.addstr("UNDERLINE! ", curses.color_pair(i) | curses.A_UNDERLINE)
            stdscr.addstr("BLINK! ", curses.color_pair(i) | curses.A_BLINK)
            stdscr.addstr("DIM! ", curses.color_pair(i) | curses.A_DIM)
            stdscr.addstr("REVERSE! ", curses.color_pair(i) | curses.A_REVERSE)
    stdscr.refresh()
    stdscr.getch()

if __name__ == '__main__':
    print "init..."
    curses.wrapper(main)
nosklo
Your code does fail under Windows (x64) with this error:AttributeError: 'module' object has no attribute 'wrapper'
Sorin Sbarnea
@Sorin Sbarnea: Accordingly to python curses official documentation in http://docs.python.org/library/curses.html , the curses module is not supported on windows. Maybe you got this error instead of "No Such Module" or something like this, because you probably named your test file "curses.py" so it is importing itself.
nosklo
+2  A: 

I have created a cross-platform package to print colored terminal text from Python:

http://pypi.python.org/pypi/colorama

It works by making ANSI escape character sequences work on Windows.

So once you have called colorama.init(), you can print ANSI escape sequences to create colored terminal output. You do this manually (print '/033[2m') or using colorama's shorthand (print Fore.RED) or using an existing library like termcolor. On Linux and Macs, this will work just the same as it always has. On Windows, these characters get intercepted when they reach sys.stdout.write(), and converted into win32 calls instead.

It only works for colors and dim/bright text, not for moving the cursor nor clearing the screen or all the other things ANSI characters can do.

Feedback much appreciated.

Tartley
+5  A: 

the answer is http://pypi.python.org/pypi/colorama for all cross-platform coloring in python

nbv4
As the author of Colorama, thanks for the mention @nbv4. I'll try and clarify a bit: Colorama aims to let Python programs print colored terminal text on all platforms, using the same ANSI codes as described in many other answers on this page. On Windows, Colorama strips these ANSI characters from stdout and converts them into equivalent win32 calls for colored text. On other platforms, Colorama does nothing. Hence you can use ANSI codes, or modules like Termcolor, and with Colorama, they 'just work' on all platforms. Is that idea, anyhow.
Tartley
A: 

Go to http://en.wikipedia.org/wiki/List_of_Unicode_characters#Block_elements There is a list of block elements(It requires Unicode). Or use ascii character 24 or 26.