def init(args): """Initialise the UI, including logging""" if args["--vverbose"]: level = "DEBUG" elif args["--verbose"]: level = "INFO" else: level = None global QUIET global VERBOSE QUIET = args["--quiet"] VERBOSE = args["--verbose"] or args["--vverbose"] root_logger = logging.getLogger("hark_lang") if not args["--no-colours"]: import coloredlogs cf.use_true_colors() cf.use_palette(UI_COLORS) cf.update_palette(UI_COLORS) if level: coloredlogs.install( fmt="[%(asctime)s.%(msecs)03d] %(name)-25s %(message)s", datefmt="%H:%M:%S", level=level, logger=root_logger, ) else: cf.disable() # FIXME Logger doesn't have basicConfig if level: root_logger.basicConfig(level=level)
def _gradient(start, end, steps): colors = Color(start).range_to(Color(end), steps) palette = {} for c in colors: h = c.hex_l.lstrip("#") name = "hex" + h palette[name] = "#" + h yield name cf.update_palette(palette)
def std_input(prompt="", style=None, palette=None): """ Very simple Python2/3-compatible input function handling prompt styling. :param prompt: prompt message :param style: colorful styling function, e.g. red_on_green (for green foreground and red background colors) :param palette: dictionary for defining new styles """ if style is not None: colorful.update_palette(palette or {}) if isinstance(style, (list, tuple, set)): style = "_".join(style) prompt = colored(prompt, style=style) return (input(prompt) if PYTHON3 else raw_input(prompt)).strip()
def std_input(prompt="", style=None, palette=None): """ Very simple Python2/3-compatible input method handling prompt styling. :param prompt: prompt message :param style: colorful styling function, e.g. red_on_green (for green foreground and red background colors) :param palette: dictionary for defining new styles """ colorful.update_palette(palette or {}) if style is not None: if isinstance(style, (list, tuple, set)): style = "_".join(style) prompt = getattr(colorful, style)(prompt) try: _ = raw_input(prompt) except NameError: _ = input(prompt) return _.strip()
def styleattrs_to_colorful(attrs): c = colorful.reset if attrs['color'] or attrs['bgcolor']: # Colorful doesn't have a way to directly set Hex/RGB # colors- until I find a better way, we do it like this :) accessor = '' if attrs['color']: colorful.update_palette({'peprintCurrFg': attrs['color']}) accessor = 'peprintCurrFg' if attrs['bgcolor']: colorful.update_palette({'peprintCurrBg': attrs['bgcolor']}) accessor += '_on_peprintCurrBg' c &= getattr(colorful, accessor) if attrs['bold']: c &= colorful.bold if attrs['italic']: c &= colorful.italic if attrs['underline']: c &= colorful.underline return c
print(cf.bold_white('Hello World')) # create a colored string using `str.format()` print('{c.bold}{c.lightCoral_on_white}Hello World{c.reset}'.format(c=cf)) # nest colors print(cf.red('red {0} red'.format(cf.white('white')))) print(cf.red('red' + cf.white(' white ', nested=True) + 'red')) # combine styles with strings print(cf.bold & cf.red | 'Hello World') # use true colors cf.use_true_colors() # extend default color palette cf.update_palette({'mint': '#c5e8c8'}) print(cf.mint_on_snow('Wow, this is actually mint')) # choose a predefined style cf.use_style('solarized') # print the official solarized colors print(cf.yellow('yellow'), cf.orange('orange'), cf.red('red'), cf.magenta('magenta'), cf.violet('violet'), cf.blue('blue'), cf.cyan('cyan'), cf.green('green')) # directly print with colors cf.print('{c.bold_blue}Hello World{c.reset}') # choose specific color mode for one block with cf.with_8_ansi_colors() as c:
COURSE_BASE_URL = '{}/courses'.format(BASE_URL) COURSE_OUTLINE_BASE_URL = '{}/course_home/v1/outline'.format(BASE_API_URL) XBLOCK_BASE_URL = '{}/xblock'.format(BASE_URL) LOGIN_API_URL = '{}/user/v1/account/login_session/'.format(BASE_API_URL) # Chunk size to download videos in chunks VID_CHUNK_SIZE = 1024 # Override colorful palette ci_colors = { 'green': '#42ba96', 'orange': '#ffc107', 'red': '#df4759', 'blue': '#5dade2' } cf.update_palette(ci_colors) # Is raised when login attempt fails class EdxLoginError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) # Is raised when the course cannot be fetched class EdxInvalidCourseError(Exception): def __init__(self, value): self.value = value def __str__(self):
# A missing load statement in colorful 0.53 (the currently-released version # as of 2019-08-29) means the COLORNAMES_COLOR palette was actually not # defined until version 0.54 (c.f. issue #31 and the commit at # https://github.com/timofurrer/colorful/commit/8e3ea7293ca5a5d98aa427116211992088ffc9fc # This loads the file directly, and as a fallback, defines the colors we need. try: rgb_file = path.join(colorful.__path__[0], 'data/rgb.txt') if path.exists(rgb_file): if __debug__: log('loading colorful colors from {}', rgb_file) colorful.setup(colorpalette=rgb_file) else: if __debug__: log('cannot find colorful rgb.txt file') except Exception: colorful.update_palette({ 'springGreen4': (0, 139, 69), }) # The following defines the basic styles we use in this application. # Regarding the ones like 'bold': There are more possible using the Python # colorful and other packages, but not all work on all platforms # (particularly Windows) and not all are that useful in pratice. Note: the # following have to be defined after the palette above is loaded into # "colorful", or else the colors used below will not be defined when the # _COLORS dictionary is created at load time. _STYLES = { 'info': colorful.springGreen4, 'warn': colorful.orange, 'warning': colorful.orange, 'error': colorful.red,
import colorful colorful.update_palette({'cyanLight': '#2aa198'}) def style_info(text): return colorful.magenta(f'{text}', nested=True) def style_warn(text): return colorful.yellow(f'{text}', nested=True) def style_error(text): return colorful.red(f'{text}', nested=True) def style_head(text): return colorful.green(f'{text}', nested=True) def style_prompt(text): return colorful.bold_cyan(f'{text}', nested=True) def style_text(text): return colorful.white(f'{text}', nested=True) def style_highlight(text): return colorful.bold(f'{text}', nested=True)
#!/usr/bin/env python3 import sys import random from uuid import uuid4 from time import sleep from faker import Faker import colorful as color fake = Faker() color.use_true_colors() color.update_palette({'darkred': '#c11b55'}) def random_color(text): out = '' while random.randint(0, 1): styles = [ 'bold', 'italic', 'underlined', 'blinkslow', 'blinkrapid', 'struckthrough' ] out += random.choice(styles) out += '_' out += random.choice(list(color.colorful.__dict__['_colorpalette'].keys())) if random.randint(0, 1): out += '_on_' out += random.choice( list(color.colorful.__dict__['_colorpalette'].keys())) return getattr(color, out)(text)
C. Show Playlist ---------------- 1. Ask the user which playlist they want to see 2. Print the contents of the playlist """ from pathlib import Path import regex from sys import stderr import colorful as cf cf.update_palette({ 'prompt': "#00FF7F", # green 'option': "#E6DB74", # yellow #'title': "#00CED1", # cyan 'title': "#00BFFF", # blue 'subtitle': "#d33682", # magenta 'error': "#dc322f", # red }) DATADIR = Path.cwd() / "data" / "playlists" INVALID_CHARS = regex.compile(r'[^ A-Za-z0-9]') def error(message): print(cf.error | "Error:", message, file=stderr) def header(title): """Print the bolded title""" print(cf.bold & cf.underlined & cf.title | title)
'turquoise4': (0, 134, 139), 'violet': (238, 130, 238), 'wheat': (245, 222, 179), 'wheat1': (255, 231, 186), 'wheat2': (238, 216, 174), 'wheat3': (205, 186, 150), 'wheat4': (139, 126, 102), 'white': (255, 255, 255), 'yellow': (255, 255, 0), 'yellow1': (255, 255, 0), 'yellow2': (238, 238, 0), 'yellow3': (205, 205, 0), 'yellow4': (139, 139, 0), } colorful.update_palette(_COLORS) # The following defines the basic styles we use in this application. # Regarding the ones like 'bold': There are more possible using the Python # colorful and other packages, but not all work on all platforms # (particularly Windows) and not all are that useful in pratice. Note: the # following have to be defined after the palette above is loaded into # "colorful", or else the colors used below will not be defined when the # _COLORS dictionary is created at load time. _STYLES = { 'info': colorful.springgreen4, 'warn': colorful.orange, 'warning': colorful.orange, 'error': colorful.red, 'fatal': colorful.red & colorful.bold & colorful.underlined,