• Stars
    star
    520
  • Rank 81,996 (Top 2 %)
  • Language
    Python
  • License
    MIT License
  • Created about 7 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Terminal string styling done right, in Python 🐍 🎉

colorful

Actions Status codecov.io PyPI version PyPI PyPI

Terminal string styling done right, in Python 🎉

Here's a tease

colorful example

import colorful as cf

# create a colored string using clever method translation
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:
    print(c.bold_green('colorful is awesome!'))

# create and choose your own color palette
MY_COMPANY_PALETTE = {
    'companyOrange': '#f4b942',
    'companyBaige': '#e8dcc5'
}
with cf.with_palette(MY_COMPANY_PALETTE) as c:
    print(c.companyOrange_on_companyBaige('Thanks for choosing our product!'))

# use f-string (only Python >= 3.6)
print(f'{cf.bold}Hello World')

# support for chinese
print(cf.red('你好'))

Key Features

  • expressive and consistent API (docs)
  • support for different color modes (8 ANSI, 256 ANSI, true colors) (docs)
  • support for predefined awesome styles (solarized, ...) (docs)
  • support for custom color palettes (docs)
  • support nesting styles (docs)
  • support for different platforms (using colorama on Windows)
  • context managers for clean color mode, color palette or style switch (docs)
  • support len() on colored strings (docs)
  • support color names from X11 rgb.txt (docs)
  • no dependencies

Usage

colorful supports all major Python versions: 3.5, 3.6 and 3.7, 3.8, 3.9, 3.10, 3.11.
We recommend to use the latest version released on PyPI:

pip install colorful

colorful does not require any special setup in order to be used:

import colorful as cf

print(cf.italic_coral_on_beige('Hello World'))
print(cf.italic & cf.coral_on_beige | 'Hello World')
print('{c.italic_coral_on_beige}Hello World{c.reset}'.format(c=cf))

Note: the entire documentation assumes colorful to be imported as cf.

See the Style a string section for more information!

Color modes

These days terminals not only support the ancient 8 ANSI colors but often they support up to 16 Million colors with true color. And if they don't support true color they might support the 256 ANSI color palette at least.

colorful supports the following color modes:

  • no colors / disable (cf.NO_COLORS)
  • 8 colors -> 8 ANSI colors (cf.ANSI_8_COLORS)
  • 256 colors -> 256 ANSI color palette (8bit cf.ANSI_256_COLORS)
  • 16'777'215 colors -> true color (24bit, cf.TRUE_COLORS)

By default colorful tries to auto detect the best supported color mode by your terminal. Consult cf.terminal for more details.

However, sometimes it makes sense to specify what color mode should be used.
colorful provides multiple ways to do so:

(1) specify color mode globally via Python API

cf.disable()
cf.use_8_ansi_colors()
cf.use_256_ansi_colors()
cf.use_true_colors()

If you change the color mode during runtime it takes affect immediately and globally.

(2) enforce color mode globally via environment variable

COLORFUL_DISABLE=1 python eggs.py  # this process will not use ANY coloring
COLORFUL_FORCE_8_COLORS=1 python eggs.py  # this process will use 8 ANSI colors by default
COLORFUL_FORCE_256_COLORS=1 python eggs.py  # this process will use 256 ANSI colors by default
COLORFUL_FORCE_TRUE_COLORS=1 python eggs.py  # this process will use true colors by default

(3) specify color mode locally via Python API (contextmanager)

with cf.with_8_ansi_colors() as c:
    print(c.italic_coral_on_beige('Hello world'))

with cf.with_256_ansi_colors() as c:
    print(c.italic_coral_on_beige('Hello world'))

with cf.with_true_colors() as c:
    print(c.italic_coral_on_beige('Hello world'))

Color palette

colorful's Python API is based on color names like in cf.bold_white_on_black('Hello'). During runtime these color names are translated into proper ANSI escape code sequences supported by the color mode in use. However, all color names are registered in a color palette which is basically a mapping between the color names and it's corresponding RGB value. Very much like this:

color_palette_example = {
    'black': '#000000',
    'white': '#FFFFFF',
}

Note: Depending on the color mode which is used the RGB value will be reduced to fit in the value domain of the color mode.

The default color palette is the X11 rgb.txt palette - it's shipped with colorful, thus, you don't have to provide your own. colorful ships with a second built-in color palette called colornames. Those colors are from the curated list of the color-names repository. You can use those via the cf.setup() method, like this:

cf.setup(colorpalette=cf.COLORNAMES_COLORS)

If you wish to have another color palette from a file as your default color palette you can set the COLORFUL_DEFAULT_COLOR_PALETTE environment variable to this file:

COLORFUL_DEFAULT_COLOR_PALETTE=/usr/share/X11/rgb.txt python spam.py

The file either has to be a txt file like the X11 rgb.txt or a JSON file:

[
    {"name": "18th Century Green", "hex":"#a59344"},
    {"name": "1975 Earth Red", "hex":"#7a463a"}
]

Custom color palette

colorful supports to update or replace the default color palette with custom colors. The colors have to be specified as RGB hex or channel values:

# corporate identity colors
ci_colors = {
    'mint': '#c5e8c8',  # RGB hex value
    'darkRed': '#c11b55',  # RGB hex value
    'lightBlue': (15, 138, 191)  # RGB channel triplet
}

# replace the default palette with my custom one
cf.use_palette(ci_colors)
# update the default palette with my custom one
cf.update_palette(ci_colors)

# we can use these colors
print(cf.italic_mint_on_darkRed('My company'))

Styles

colorful supports some famous color palettes using what's called styles in colorful:

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'))

The following styles are already supported:

solarized - Website
solarized colors
monokai
monokai colors

Note: if you know some awesome color palettes which could be a new style in colorful, please contribute it!

Style a string

colorful provides multiple ways to use style a string. Most useful and expressive is probably the method syntax where you specify the modifiers and colors in the method name itself and pass the string as argument to this method. However, you can use all the following methods to achive similars things:

(1) Style a string with a method call cf.[<modifiers...>]_[<fgColor>]_[on_<bgColor>](str, nested=False)

print(cf.red('I am red'))
print(cf.italic_yellow('I am italic and yellow'))
print(cf.black_on_white('I am black on white'))

The method syntax can be one of:

  • cf.<modifier>
  • cf.<modifier1>_<modifier2>
  • cf.<fg_color>
  • cf.on_<bg_color>
  • cf.<modifiers>_<fg_color>
  • cf.<modifiers>_<bg_color>
  • cf.<fg_colors>_on_<bg_color>
  • cf.<modifiers>_<fg_color>_on_<bg_color>

Note that multiple <modifier>s can be specified at once.

Available modifiers are:

  • reset (explicitely reset all styles before the passed argument)
  • bold
  • dimmed (not widely supported)
  • italic
  • underlined
  • blinkslow
  • blinkrapid
  • inversed (not widely supported)
  • concealed (not widely supported)
  • struckthrough

The available colors depend on the color palette you are using. By default all X11 rgb.txt colors are available.

The type of the return value of such a style method is colorful.ColorfulString. It correctly supports all str() methods including len().

As you can see from the syntax in the section name, colorful supports nesting styles. See Nesting styles.

(2) Style a string with & and |

colorful implements the __or__ and __and__ protocol to combine styles and pipe strings into them:

print(cf.bold & cf.red | 'Hello World')
print(cf.bold_red_on_black | 'Hello World')
print(cf.bold | cf.red_on_black('Hello World')

Note: the piping | has the same effect as doing a method call to the style.
So you could do (cf.bold & cf.red)('Hello World')

(3) Style a string with cf.format(string, *args, **kwargs)

print(cf.format('{c.red}I am {what}{c.close_fg_color}', what='red'))
# alternatively to ``c.close_fg_color`` you can reset every style with ``c.reset``
print(cf.format('{c.red}I am red{c.reset}'))

print(cf.format('{c.italic_yellow}I am italic and yellow{c.no_italic}{c.close_fg_color}'))
print(cf.format('{c.black_on_white}I am black on white{c.close_fg_color}{c.close_bg_color}'))

colorful will replace the {c.<style>} with the correspnding style. It's not necessary to pass a colorful object for c to format() - colorful will handle that. Every other format argument ({<name>}) has to be pass to the cf.format() call as args or kwarg.

Note: The same syntax, modifiers and colors for the style in {c.<style>} can be used as for (1) Style a string with a method call.

(4) Style and print a string with cf.print(*strings, sep=' ', end='\n', file=sys.stdout, flush=False)

cf.print('{c.italic_yellow}I am italic and yellow{c.no_italic}{c.close_fg_color}')
cf.print('{c.red}I am red{c.reset}', end='', file=open('log.txt', 'a+'))

The cf.print() method accepts the same arguments as the Python 3.X built-in print() function.

(5) Style a string with str.format()

print('{c.red}I am red{c.close_fg_color}'.format(c=cf))
# alternatively to ``c.close_fg_color`` you can reset every style with ``c.reset``
print('{c.red}I am red{c.reset}'.format(c=cf))

print('{c.italic_yellow}I am italic and yellow{c.no_italic}{c.close_fg_color}'.format(
    c=cf))
print('{c.black_on_white}I am black on white{c.close_fg_color}{c.close_bg_color}'.format(
    c=cf))

Note: The same syntax, modifiers and colors for the style in {c.<style>} can be used as for (1) Style a string with a method call.

Nesting styles

colorful supports to nest styles with it's method call syntax when setting the parameter nested to True. If you are using str.format() like in the first example below you don't even need the nested=True flag!

The following examples show the behavior:

print(cf.red('red {0} red'.format(cf.white('white'))))
print(cf.red('red' + cf.white(' white ', nested=True) + 'red'))

# if using ``nested=True`` but you don't actually nest
# it's absolutely fine and will work as expected.
print(cf.red('red', nested=True) + ' default color')

Correctly support the len() protocol

colorful correctly supports the len() protocol (__len__) on the styled strings. As mentioned above, when you style a string a colorful.ColorfulString object is returned. This object returns the length (when calling len()) as it would be for the unstyled string to integrate styled strings seemlessly into your application.

>>> s = 'Hello World'
>>> len(s)
11
>>> len(cf.yellow(s))
11
>>> assert len(s) == len(cf.yellow(s))

Temporarily change colorful settings

colorful provides a hand full of convenient context managers to change the colorful settings temporarily:

(1) change color mode

Use 8 ANSI colors:

with cf.with_8_ansi_colors() as c:
    print(c.red('I am red'))

Use 256 ANSI colors:

with cf.with_256_ansi_colors() as c:
    print(c.red('I am red'))

Use true colors:

with cf.with_true_colors() as c:
    print(c.red('I am red'))

(2) change color palette

# replace the entire color palette
with cf.with_palette(my_palette) as c:
    print(c.customRed('I am custom red'))

# update the color palette
with cf.with_updated_palette(my_palette) as c:
    print(c.customRed('I am custom red'))

(3) change style

with cf.with_style('solarized') as c:
    print(c.red('I am solarized red'))

This project is published under MIT.
A Timo Furrer project.
- 🎉 -

More Repositories

1

awesome-asyncio

A curated list of awesome Python asyncio frameworks, libraries, software and resources
4,418
star
2

try

Dead simple CLI tool to try Python packages - It's never been easier! 📦
Python
705
star
3

w1thermsensor

A Python package and CLI tool to work with w1 temperature sensors like DS1822, DS18S20 & DS18B20 on the Raspberry Pi, Beagle Bone and other devices.
Python
485
star
4

russian-roulette

🍀 You want to push your luck? ... Go ahead and try your best with this CLI russian roulette! 💥
Shell
111
star
5

shellfuncs

Python API to execute shell functions as they would be Python functions
Python
101
star
6

pandoc-plantuml-filter

Pandoc filter for PlantUML code blocks
Python
99
star
7

observable

minimalist event system for Python
Python
86
star
8

WOL

C program to send wol magic packets
C
79
star
9

pandoc-mermaid-filter

Pandoc filter for mermaid code blocks
Python
71
star
10

devheart

Listen to Tux's heartbeat with this awesome Linux Kernel Module ❤️
C
58
star
11

git-russian-roulette

🍀 play russian roulette in your git repository. 🔫
Shell
44
star
12

minion-ci

minimalist, decentralized, flexible Continuous Integration Server for hackers.
Python
43
star
13

javascript-style-guide

Ein vernünftiger Ansatz für einen JavaScript-Style-Guide
35
star
14

securityheaders

🔒 CLI application to analyse Security Headers from a given URL using securityheaders.io
Python
19
star
15

musichaos

tool to tidy up your music chaos
Python
17
star
16

dropbox-cli

cli to manage your dropbox account
Python
10
star
17

ariseem

Minimalistic REST API for wake-on-lan
Python
10
star
18

leaked

Find leaked information in different kind of services
Python
9
star
19

retry-cmd

Retry commands on the command line without all the loops you always used!
Rust
9
star
20

confluo

➰ Minimalist scalable microservice framework for distributed systems using AMQP/RabbitMQ.
Python
9
star
21

.vim

vim configuration for myself.
Vim Script
6
star
22

ramlient

Access to a RAML API done right, in Python. (Feasibility)
RAML
6
star
23

ptipython-meta

Metapackage to install ptpython and ipython.
Python
6
star
24

idn-homograph-attack

Resources for "IDN Homograph Attack" for HSLU FKOM blog post testat
HTML
6
star
25

avra-atmega2560

This repository is a clone of avra version 1.3.0 with additional fixes to support the ATmega2560 chip
C
5
star
26

embedeval

NLP Embeddings Evaluation Tool
Python
4
star
27

dotfiles.attic

My personal dotfiles
Shell
4
star
28

broadcom-wl-monitormode

This is a source mirror for the broadcom wl driver version 6.30.223.141 with fixed monitor mode
C
4
star
29

hslu-pren-fs19

Implementation of the PREN FS2019 challenge at @ HSLU
Jupyter Notebook
4
star
30

saythanks-cli

Say Thanks via CLI. Uses @kennethreitz's great saythanks.io
Python
4
star
31

tag-expressions

Python implementation of Shunting-yard Algorithm to evaluate logical tag expressions
Python
3
star
32

dotfiles-2

Vim Script
3
star
33

hslu-pren-digit-cnn

Convolutional Neural Network to recognize digits used in the PREN class @ HSLU
Jupyter Notebook
3
star
34

python3.10-pattern-matching

Python 3.10 demos
Jupyter Notebook
3
star
35

edelweiss

edelweiss. A delightful color scheme for my personal terminal stack
Lua
3
star
36

pylemon

python daemon to monitor specific directories and react on changes
2
star
37

advent-of-code

My solutions for the Advent of Code puzzles
Python
2
star
38

java-dev

Java dev environment (Vagrant, Ansible, VirtualBox, Ubuntu 16.04) for HSLU
2
star
39

hslu-webtec-testat

HSLU WebTec Testat
JavaScript
2
star
40

pysingleton

module which provides a decorator to create thread-safe singleton classes
Python
2
star
41

lightning-talk-linux-kernel-module-examples

Examples for my "Linux Kernel Modules 101" Lightning Talk ⚡
C
2
star
42

timofurrer.github.io

Personal website and blog
HTML
2
star
43

asciitable

print formatted ascii table on console
C
1
star
44

clicore

small cli to use in python programs
Python
1
star
45

hslu-roblab-behavior

Python
1
star
46

sudoku.vim

vim plugin to solve sudoku files
Python
1
star
47

.tmux

my tmux configuration
1
star
48

coverage-importlib-test

Python
1
star
49

schoolcli

This is a very useful command line interface to manage your school marks
Python
1
star
50

hslu-xml-technologies

HSLU - XML Technologies - Projektarbeit
XSLT
1
star
51

hslu-ipcv

Exercises for the IPCV class @ HSLU
Jupyter Notebook
1
star
52

hslu-dbs

HSLU - DBS
TypeScript
1
star
53

hslu-aiso

HSLU AISO Class Exercises
Jupyter Notebook
1
star
54

dotfiles

Lua
1
star