Package: colorful
colorfulTerminal string styling done right, in Python :tada:Here's a teaseimportcolorfulascf# create a colored string using clever method translationprint(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 colorsprint(cf.red('red{0}red'.format(cf.white('white'))))print(cf.red('red'+cf.white(' white ',nested=True)+'red'))# combine styles with stringsprint(cf.bold&cf.red|'Hello World')# use true colorscf.use_true_colors()# extend default color palettecf.update_palette({'mint':'#c5e8c8'})print(cf.mint_on_snow('Wow, this is actually mint'))# choose a predefined stylecf.use_style('solarized')# print the official solarized colorsprint(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 colorscf.print('{c.bold_blue}Hello World{c.reset}')# choose specific color mode for one blockwithcf.with_8_ansi_colors()asc:print(c.bold_green('colorful is awesome!'))# create and choose your own color paletteMY_COMPANY_PALETTE={'companyOrange':'#f4b942','companyBaige':'#e8dcc5'}withcf.with_palette(MY_COMPANY_PALETTE)asc: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 chineseprint(cf.red('你好'))Key Featuresexpressive 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)supportlen()on colored strings (docs)support color names fromX11 rgb.txt(docs)no dependenciesUsagecolorfulsupports all major Python versions:3.5,3.6and3.7,3.8,3.9,3.10,3.11,3.12.We recommend to use the latest version released onPyPI:pipinstallcolorfulcolorfuldoes not require any special setup in order to be used:importcolorfulascfprint(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 assumescolorfulto be imported ascf.See theStyle a stringsection for more information!Color modesThese days terminals not only support the ancient 8 ANSI colors but often they support up to 16 Million colors withtrue color. And if they don't supporttrue colorthey might support the256 ANSI color paletteat least.colorfulsupports 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 (8bitcf.ANSI_256_COLORS)16'777'215 colors -> true color (24bit,cf.TRUE_COLORS)By defaultcolorfultries to auto detect the best supported color mode by your terminal. Consultcf.terminalfor more details.However, sometimes it makes sense to specify what color mode should be used.colorfulprovides multiple ways to do so:(1) specify color mode globally via Python APIcf.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 variableCOLORFUL_DISABLE=1pythoneggs.py# this process will not use ANY coloringCOLORFUL_FORCE_8_COLORS=1pythoneggs.py# this process will use 8 ANSI colors by defaultCOLORFUL_FORCE_256_COLORS=1pythoneggs.py# this process will use 256 ANSI colors by defaultCOLORFUL_FORCE_TRUE_COLORS=1pythoneggs.py# this process will use true colors by default(3) specify color mode locally via Python API (contextmanager)withcf.with_8_ansi_colors()asc:print(c.italic_coral_on_beige('Hello world'))withcf.with_256_ansi_colors()asc:print(c.italic_coral_on_beige('Hello world'))withcf.with_true_colors()asc:print(c.italic_coral_on_beige('Hello world'))Color palettecolorful's Python API is based oncolor nameslike incf.bold_white_on_black('Hello'). During runtime thesecolor namesare translated into properANSI escape codesequences supported by thecolor modein use. However, allcolor namesare registered in acolor palettewhich is basically a mapping between thecolor namesand 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 theX11 rgb.txtpalette - it's shipped withcolorful, thus, you don't have to provide your own.colorfulships with a second built-incolor palette calledcolornames.
Those colors are from the curated list of thecolor-namesrepository.
You can use those via thecf.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 theCOLORFUL_DEFAULT_COLOR_PALETTEenvironment variable to this file:COLORFUL_DEFAULT_COLOR_PALETTE=/usr/share/X11/rgb.txtpythonspam.pyThe 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 palettecolorfulsupports 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 colorsci_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 onecf.use_palette(ci_colors)# update the default palette with my custom onecf.update_palette(ci_colors)# we can use these colorsprint(cf.italic_mint_on_darkRed('My company'))Stylescolorfulsupports some famous color palettes using what's calledstylesin colorful:cf.use_style('solarized')# print the official solarized colorsprint(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 -WebsitemonokaiNote: if you know some awesome color palettes which could be a new style in colorful, please contribute it!Style a stringcolorfulprovides multiple ways to use style a string. Most useful and expressive is probably themethod syntaxwhere 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 callcf.[<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)bolddimmed (not widely supported)italicunderlinedblinkslowblinkrapidinversed (not widely supported)concealed (not widely supported)struckthroughThe available colors depend on thecolor paletteyou are using. By default allX11 rgb.txt colorsare available.The type of the return value of such astyle methodiscolorful.ColorfulString. It correctly supports allstr()methods includinglen().As you can see from the syntax in the section name,colorfulsupports nesting styles. SeeNesting styles.(2) Style a string with&and|colorfulimplements 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 withcf.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}'))colorfulwill replace the{c.<style>}with the correspnding style. It'snotnecessary to pass a colorful object forctoformat()- colorful will handle that. Every other format argument ({<name>}) has to be pass to thecf.format()call asargsorkwarg.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 withcf.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+'))Thecf.print()method accepts the same arguments as the Python 3.Xbuilt-in print()function.(5) Style a string withstr.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 stylescolorfulsupports to nest styles with it'smethod call syntaxwhen setting the parameternestedtoTrue.
If you are usingstr.format()like in the first example below you don't even need thenested=Trueflag!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 thelen()protocolcolorfulcorrectly supports thelen()protocol (__len__) on the styled strings. As mentioned above, when you style a string acolorful.ColorfulStringobject is returned. This object returns the length (when callinglen()) as it would be for theunstyled stringto integrate styled strings seemlessly into your application.>>>s='Hello World'>>>len(s)11>>>len(cf.yellow(s))11>>>assertlen(s)==len(cf.yellow(s))Temporarily change colorful settingscolorfulprovides a hand full of convenient context managers to change the colorful settings temporarily:(1) change color modeUse 8 ANSI colors:withcf.with_8_ansi_colors()asc:print(c.red('I am red'))Use 256 ANSI colors:withcf.with_256_ansi_colors()asc:print(c.red('I am red'))Use true colors:withcf.with_true_colors()asc:print(c.red('I am red'))(2) change color palette# replace the entire color palettewithcf.with_palette(my_palette)asc:print(c.customRed('I am custom red'))# update the color palettewithcf.with_updated_palette(my_palette)asc:print(c.customRed('I am custom red'))(3) change stylewithcf.with_style('solarized')asc:print(c.red('I am solarized red'))This project is published underMIT.ATimo Furrerproject.- :tada: -