This document describes the current stable version of Celery (3.1). For development docs, go here.
# -*- coding: utf-8 -*-
"""
celery.utils.term
~~~~~~~~~~~~~~~~~
Terminals and colors.
"""
from __future__ import absolute_import, unicode_literals
import platform
from functools import reduce
from kombu.utils.encoding import safe_str
from celery.five import string
__all__ = ['colored']
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
OP_SEQ = '\033[%dm'
RESET_SEQ = '\033[0m'
COLOR_SEQ = '\033[1;%dm'
fg = lambda s: COLOR_SEQ % s
IS_WINDOWS = platform.system() == 'Windows'
[docs]class colored(object):
"""Terminal colored text.
Example::
>>> c = colored(enabled=True)
>>> print(str(c.red('the quick '), c.blue('brown ', c.bold('fox ')),
... c.magenta(c.underline('jumps over')),
... c.yellow(' the lazy '),
... c.green('dog ')))
"""
def __init__(self, *s, **kwargs):
self.s = s
self.enabled = not IS_WINDOWS and kwargs.get('enabled', True)
self.op = kwargs.get('op', '')
self.names = {'black': self.black,
'red': self.red,
'green': self.green,
'yellow': self.yellow,
'blue': self.blue,
'magenta': self.magenta,
'cyan': self.cyan,
'white': self.white}
def _add(self, a, b):
return string(a) + string(b)
def _fold_no_color(self, a, b):
try:
A = a.no_color()
except AttributeError:
A = string(a)
try:
B = b.no_color()
except AttributeError:
B = string(b)
return ''.join((string(A), string(B)))
[docs] def embed(self):
prefix = ''
if self.enabled:
prefix = self.op
return ''.join((string(prefix), string(reduce(self._add, self.s))))
def __unicode__(self):
suffix = ''
if self.enabled:
suffix = RESET_SEQ
return string(''.join((self.embed(), string(suffix))))
def __str__(self):
return safe_str(self.__unicode__())
def __repr__(self):
return repr(self.no_color())
def __add__(self, other):
return string(self) + string(other)