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
2010-02-24 22:49:55
+3
A:
curses
will allow you to use colors properly for the type of terminal that is being used.
Ignacio Vazquez-Abrams
2010-02-24 22:50:58
+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
2010-02-24 22:55:21
+1 especially for `sys.stdout.isatty()`
Nifle
2010-02-24 22:59:11
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
2010-02-24 23:02:38
`unbuffer` can do that, so you're not stuck if there's no override.
Ignacio Vazquez-Abrams
2010-02-24 23:18:47
@Ignacio, cool I wonder why debian doesn't have an unbuffer package :(
gnibbler
2010-02-24 23:26:22
@gnibbler: unbuffer is part of expect.
Ignacio Vazquez-Abrams
2010-02-24 23:30:24
found it - debian hides it in `expect-dev` under the name `expect_unbuffer`
gnibbler
2010-02-24 23:32:15