tags:

views:

626

answers:

4

I was wondering if anyone knows how to set the color of the text that shows up in the shell. I noticed the 'ls' uses a couple different colors when printing out information to the screen (on my Linux box), was wondering if I could take advantage of that in Python.

+2  A: 

All the major color codes are given at https://www.siafoo.net/snippet/88

Matthew Flaschen
+3  A: 

curses will allow you to use colors properly for the type of terminal that is being used.

Ignacio Vazquez-Abrams
+7  A: 

Use Curses or ANSI escape sequences. Before you start spouting escape sequences, you should check that stdout is a tty. You can do this with sys.stdout.isatty(). Here's a function pulled from a project of mine that prints output in red or green, depending on the status, using ANSI escape sequences:

def hilite(string, status, bold):
    attr = []
    if status:
        # green
        attr.append('32')
    else:
        # red
        attr.append('31')
    if bold:
        attr.append('1')
    return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
Dietrich Epp
+1 especially for `sys.stdout.isatty()`
Nifle
It's also nice to have an override for the case that the output is not a tty, but you still want the colour - say you are just filtering lines with sed or grep
gnibbler
`unbuffer` can do that, so you're not stuck if there's no override.
Ignacio Vazquez-Abrams
@Ignacio, cool I wonder why debian doesn't have an unbuffer package :(
gnibbler
@gnibbler: unbuffer is part of expect.
Ignacio Vazquez-Abrams
found it - debian hides it in `expect-dev` under the name `expect_unbuffer`
gnibbler
A: 

have a look at http://www.pixelbeat.org/talks/python/ls.py

pixelbeat