Colored output with Python

Here's my stupid way of getting colored output from a Python script when run from the command line.

First, define one function per desired color:

{% highlight python %} def blue(message): return '\033[1;34m%s\033[1;m' % (message) def green(message): return '\033[1;32m%s\033[1;m' % (message) def red(message): return '\033[1;41m%s\033[1;m' % (message) def yellow(message): return '\033[1;33m%s\033[1;m' % (message) {% endhighlight %}

And then in the script, pass the message that you need to appear in color like this:

{% highlight python %} print red('File not found!') {% endhighlight %}

Note that if the Python script is meant to run via cron, then you will get some ugly text in emails from cron, since escape codes are not interpreted or removed from the output.

Posted on