ACarter
ACarter

Reputation: 5697

Easy cross-platform python way of colouring text in the command line/shell

Bascially, I want an easy(ish), cross-platform way of colouring text in the command line/shell.

I would really like this to not involve importing a module, but because cross-platform support is pretty complicated, I know it will probably have to.

I don't need it to be too elaborate though, just a few basic colours will do.

Upvotes: 1

Views: 1360

Answers (4)

Tariq Tayebi
Tariq Tayebi

Reputation: 13

Try ColourScript.

Not only does it have colours, it has background colours, bright colours, dark colours, data, and every colour named in programming (r,g,b), which is not possible in other modules and in octal (what you are doing right now).

pip install ColourScript.

https://pypi.org/project/ColourScript/

Upvotes: 0

mata
mata

Reputation: 69042

Writing ANSI excape sequences doesn't require anything fancy and should be fairly easy.

Here is a basic exaple that show how it can be done manually.*

Or you could also have a look of libraries like termcolor or colorama for reference.

*edit: just seen that this example isn't really fully functional. to make it work 33[ has to be replaced with \033[

Upvotes: 3

Thomas Orozco
Thomas Orozco

Reputation: 55215

You'll have to use a module if you want something cross-platform / slightly complicated.

I'd recommend using pypi.python.org/pypi/colorama, which is cross-platform.

Upvotes: 1

tylerl
tylerl

Reputation: 30857

The mechanism for coloring terminal output is pretty universal. It's done by echoing escape commands into the output stream.

http://en.wikipedia.org/wiki/ANSI_escape_code

The real key is determining whether the terminal you're looking at supports coloring. If, for example, output is being redirected to a file, then the escape sequences will just clutter your output stream, since you're probably eventually be reading the file with a text editor.

Determining the capabilities of your terminal window is generally handled through something called "termcap", and there are several libraries for that purpose, with that exact name. This is also often rolled into more capable libraries, like curses.

And, it turns out, you're in luck: http://docs.python.org/library/curses.html

Upvotes: 2

Related Questions