Giter Club home page Giter Club logo

colorful's Introduction

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, 3.12.
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.
- 🎉 -

colorful's People

Contributors

0ki avatar amonsch avatar asherf avatar carlwgeorge avatar edouard-lopez avatar fliiiix avatar keturn avatar koterpillar avatar lcnittl avatar mociof avatar plastictortoise avatar qcha0 avatar timofurrer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

colorful's Issues

Support indexing and slicing

Hello,

You say in the readme that:

It correctly supports all str() methods including len().

But it seems it does not support basic indexing or slicing:

image

Could you please fix or implement it?
I need this kind of functionality to be able to support colors in my progress bar project. I was wondering if I'd implement colorizing and len and indexing and slicing myself, but thankfully found this project of yours, it is missing little to fit my need perfectly. Thanks.

My project is in: https://github.com/rsalmei/alive-progress
alive-progress

Potentially messed up color codes

Description

Hi there, seems like the colors are messed up...
I've copied your example code and ran it on my machine and in an isolated venv with the same result:

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('你好'))

And it shows the following:
image

Environment

  • OS: Windows 10 Enterprise (10.0.17763)
  • Arch: AMD64
  • Python: 3.9.12
  • pip freeze (installed venv modules): colorama==0.4.4, colorful==0.5.4

Really appreciate the module, hit me up if you need further information!!!

Bug: DEFAULT_ENCODE is None when no TTY allocation

If there no TTY, for example run python script with ">" a file.
then sys.stdout.encoding will be None.
in core.py line 212, need to set a default encode 'utf-8" when DEFAULT_ENCODE is None.

Traceback (most recent call last):
  File "main_wrapper.py", line 27, in <module>
    sys.exit(main())
  File "main_wrapper.py", line 22, in main
    return `radish_main()`
  File "/usr/lib/python2.7/site-packages/radish/errororacle.py", line 54, in _decorator
    handle_exception(e)
  File "/usr/lib/python2.7/site-packages/radish/errororacle.py", line 75, in handle_exception
    write_error(exception)
  File "/usr/lib/python2.7/site-packages/radish/errororacle.py", line 25, in write_error
    console_write("{0}: {1}".format(colorful.bold_red("Error"), colorful.red(text)))
  File "/usr/lib/python2.7/site-packages/colorful/core.py", line 532, in __call__
    return self.evaluate(string, nested)
  File "/usr/lib/python2.7/site-packages/colorful/core.py", line 519, in evaluate
    style_string(string, self.style, self.colormode, nested))
  File "/usr/lib/python2.7/site-packages/colorful/core.py", line 212, in style_string
    string = string.decode(DEFAULT_ENCODE)
TypeError: decode() argument 1 must be string, not None

No color in terminal

related: fish-shell/fish-shell#5686


Hello,
Thanks for the lib, look promising for my project.

Actual

When invoking the script with Python (above) I got the correct output, same when invoking fish_prompt manually (middle). However, when it's automatically invoked by fish there is no color (below).

dev_231

Python

import colorful


def prompt(last_command_status=0):
    print(colorful.red('red'))
    symbol = '❯'
    return symbol


if __name__ == "__main__":
    print("%s " % (prompt()))

Fish

Above code is invoked through a snippet in ~/.config/fish/functions/fish_prompt.fish:

function fish_prompt
    python3 ~/projects/purish/pure/prompt.py $status
end

Question

Am I missing something here?

Support freezing with PyInstaller

Is your Feature Request related to a problem? Please describe.
If you try to package an application that depends on colorful (for example in a transitive dependency, like prettyprinter), the PyInstaller process will succeed, but if fails at runtime because it cannot find the data files.

Describe the solution you'd like

This package should include metadata to include those files in the build process.

Additional context

There's upstream support for marking this data. Here's the upstream documentation about this:

https://pyinstaller.org/en/stable/hooks.html#providing-pyinstaller-hooks-with-your-package

https://github.com/pyinstaller/hooksample

underlined vs no_underline

First, thanks for this great library, it takes away so much pain from working with this ANSI crap.

I created a wrap(string, style) function, that wraps a string in a style, then undoes that.
So wrap("hello", "underlined") would call something like getattr(colorful, style) + string + gettattr(coloful, "no_" + style).
The issue is there is no no_underlined, there's only no_underline.

https://github.com/timofurrer/colorful/blob/master/colorful/core.py#L320-L327

Looking at the list, there are a few renamings here, no_underline vs underline, no_blink vs blinkslow, no_reveal vs concealed (should be reveal or no_conceal), no_strikethrough vs struckthrough.

I think this can be fixed in a backwards-compatible way:

  1. Use active voice: dim, underline, inverse, conceal, strikethrough
  2. map {style} 1:1 to no_{style}
  3. maybe this to the translate_style function? ansi.MODIFIERS is already used in there, would reduce naming duplications.

cc @timofurrer

Colors escape sequences got stripped off during test with pytest

related: https://stackoverflow.com/q/54884561/802365


I'm re-implementing pure prompt in python so it can support more shell.

However, when testing color I got "unexecpected" behavior, i.e. one that I don't understand.

tests output

    def test_prompt_symbol_is_colored_for_successful_command():
        assert str(prompt.prompt_symbol()) == str(colors.primary('❯'))
>       assert str(prompt.prompt_symbol()) == '\x1b[38;2;155;48;255m❯\x1b[39m'
E       AssertionError: assert '❯' == '\x1b[38;2;155;48;255m❯\x1b[39m'
E         - ❯
E         + ❯   ← this one is purple

colors_test.py

def test_prompt_symbol_is_colored_for_successful_command():
    assert str(prompt.prompt_symbol()) == str(colors.primary('❯'))
    assert str(prompt.prompt_symbol()) == '\x1b[38;2;155;48;255m❯\x1b[39m'

colors.py

import colorful

primary = colorful.purple1
mute = colorful.gray

prompt.py

from pure import colors

def prompt_symbol(last_command_status=0):
    symbol = colors.primary('❯') if last_command_status == 0 else colors.danger('❯')
    return symbol

Question

The first assertion succeed, while the second failed despite the fact they should be equivalent. When I negate the first assertion the escape sequence are not present:

>       assert str(prompt.prompt_symbol()) != str(colors.primary('❯'))
E       AssertionError: assert '❯' != '❯'
E        +  where '❯' = str(<colorful.core.ColorfulString object at 0x7f545276f080>)
E        +    where <colorful.core.ColorfulString object at 0x7f545276f080> = <function prompt_symbol at 0x7f54527b79d8>()
E        +      where <function prompt_symbol at 0x7f54527b79d8> = prompt.prompt_symbol
E        +  and   '❯' = str(<colorful.core.ColorfulString object at 0x7f545276f0b8>)
E        +    where <colorful.core.ColorfulString object at 0x7f545276f0b8> = <colorful.core.Colorful.ColorfulStyle object at 0x7f54527c2278>('❯')
E        +      where <colorful.core.Colorful.ColorfulStyle object at 0x7f54527c2278> = colors.primary

Manually executing command in python REPL gives me:

>>> from pure import colors, prompt 
>>> str(colors.primary('❯'))
'\x1b[38;2;155;48;255m❯\x1b[39m'
>>> str(prompt.prompt_symbol())
'\x1b[38;2;155;48;255m❯\x1b[39m'

support string formatter's width specification

Consider

print(f"A{cf.italic_underlined_lavender('Z'):>80}")

The Z ends up in quite a different spot when color output is enabled vs disabled!

I believe that since ColorfulString already knows how to calculate its printable length, it would be able to appropriately handle field width specifications if it were to implement __format__.

That method is used by both the f-string literals and format().

Trying to use json palette crashes because of file encoding

Important notices
Before you add a new report, we ask you kindly to acknowledge the following:

[-] I have read the contributing guide lines at https://github.com/timofurrer/colorful/blob/master/.github/CONTRIBUTING.md
THIS LINK IS BROKEN: https://github.com/timofurrer/colorful/blob/master/.github/CONTRIBUTING.md

[-] I have read and respect the code of conduct at https://github.com/timofurrer/colorful/blob/master/.github/CODE_OF_CONDUCT.md
OK

[-] I have searched the existing issues and I'm convinced that mine is new.
YES, ALTHOUGH SOME MIGHT BE RELATED

Describe the bug
A clear and concise description of what the bug is.

import json

from colorful import Colorful, colors
from colorful.core import COLORNAMES_COLORS_PATH

cf = Colorful(colorpalette=COLORNAMES_COLORS_PATH)  # this is going to crash
colors.parse_json_color_file(COLORNAMES_COLORS_PATH)  # this is the method that is actually crashing

with open(COLORNAMES_COLORS_PATH, encoding="utf8") as f:  # this is how you fix it
    colorpalette = json.load(f)

Environment and Version

  • OS (incl. terminal and shell used): windows, pycharm
  • Python Version: 3.8
  • colorful Version: 0.5.4

To Reproduce
A clear and concise description of steps to reproduce the behavior
you are experiencing.

from colorful import Colorful, colors
from colorful.core import COLORNAMES_COLORS_PATH

cf = Colorful(colorpalette=COLORNAMES_COLORS_PATH)  # this is going to crash
colors.parse_json_color_file(COLORNAMES_COLORS_PATH)  # this is the method that is actually crashing

Expected behavior
A clear and concise description of what you expected to happen.

I think an easier way to extend colors with the json included on this library would be good

Screenshots
If applicable, add screenshots to help explain your problem.

Additional context
Add any other context about the problem here.

if you want to I know exactly what to do to fix it so I can make a PR, but I would want to make some changes, like the color name in the json file has spaces and upper cased letters, I would probably change that to camel case, which seems to be the standard for this library

edit: I just realized there is already a sanitize_color_palette that makes the camelcase, sorry

Support for elvish shell

related: elves/elvish#804


When running in a docker I get ANSI colour code instead of the color should get thanks to colorful module.

❯ docker run \
     --name run-pure-on-elvish \
     --rm \
     --interactive \
     --tty \
     --volume=$PWD:/home/nemo/.pure/ \
     pure-on-elvish-latest
^[[38;2;173;216;230m/home/pure/.pure^[[39m^[[26m
^[[38;2;190;190;190mmaster^[[39m^[[26m^[[38;2;190;190;190m*^[[39m^[[26m
^[[38;2;205;0;0m❯^[[39m^[[26m

However if in said container I run a Python3 prompt, it works fine:

$ python3
Python 3.6.8 (default, Jan 24 2019, 16:36:30)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import colorful
>>> print(colorful.red('red {0} red'.format(colorful.white('white'))))
red white red  <---------------- colored adequatly

I tried to force color in my container using -e TERM=xterm-256color without success.

Provide a way to generate 'non colorized' colorized string

This will make it easy to format output lines like:

line = 'beginning of line '
line += colorful.green('remainder of line is green')

Currently the example above creates an already-formatted string, which loses the ability to later on decide if to use the original text or the formatted one

INFO: Drop Python 2.7 and Python 3.4 support

Support for Python 2.7 will end with the beginning of 2020.
Python 3.4 has gotten it's last update a few months ago in March 2019.

I'll plan to drop Python 2.7 and Python 3.4 support sometime after September 2019.
However, I'm happy to accept PRs for a Python 2.7 and Python 3.4 maintenance branch that I could release accordingly.

Feature: Support Double Size Text

Important notices
Before you add a new request, we ask you kindly to acknowledge the following:

[x] I have read the contributing guide lines at https://github.com/timofurrer/colorful/blob/master/.github/CONTRIBUTING.md

[x] I have read and respect the code of conduct at https://github.com/timofurrer/colorful/blob/master/.github/CODE_OF_CONDUCT.md

[x] I have searched the existing issues and I'm convinced that mine is new.

Is your Feature Request related to a problem? Please describe.
I've recently been looking into various ANSI escape codes and have found that it is possible to double the text size in some terminals using ESC#4. This would be used to draw headings in console applications

Describe the solution you'd like
Add a heading/ big/ double text style to colorful to enable this

Describe alternatives you've considered
User could use the escape code in their string

Additional context
If this is something that you would like to be included I'd be happy to create a pull request

Can't support utf-8?

Using colorful can not print Chinese characters. This module supports ASCII only?

Please provide type stubs!

Hello,
thanks for this wonderful module!

Can we please have type stubs (.pyi files), to enable code-completion in IDEs?

How go back to default color pallet

How can I go to default after setting a style?

colorful.use_style('monokai')

print colorful.magenta('color')

# looked on source code and tried these without success
# colorful.use_style('default')
# colorful.use_style('x11')
# colorful.use_style(None)
# colorful.use_style('rgb')
# colorful.use_style('colornames')
# colorful.use_style('X11 rgb.txt')
# colorful.disable()
# colorful.use_8_ansi_colors()
# colorful.use_256_ansi_colors()
# colorful.use_true_colors()

colorful.use_style('TRUE_COLORS')

print colorful.greenYellow('color')

colorful.core.ColorfulAttributeError: the color "greenYellow" is unknown. Use a color in your color palette (by default: X11 rgb.txt)

colorful dicts in system service app

I have a flask app that I run as a system service. I love using colorful for debugging purposes, but when I deploy the app as a system service, using colorful to print a dictionary is producing this error

TypeError: __str__ returned non-string (type dict)

Are there any environment variables I can use to prevent this?

"crimson" as an X11 color is missing from the default color palette

Important notices
Before you add a new report, we ask you kindly to acknowledge the following:

[X] I have read the contributing guide lines at https://github.com/timofurrer/colorful/blob/master/.github/CONTRIBUTING.md

[X] I have read and respect the code of conduct at https://github.com/timofurrer/colorful/blob/master/.github/CODE_OF_CONDUCT.md

[X] I have searched the existing issues and I'm convinced that mine is new.

Describe the bug
The color "crimson" is missing from the default color palette. It's a color named on the X11 color list, but is not actually included in this library.

Environment and Version

  • OS (incl. terminal and shell used): Windows Terminal (Powershell)
  • Python Version: 3.8.3
  • colorful Version: 0.5.4

To Reproduce

import colorful as cf
print(cf.crimson("test"))

Expected behavior
The text to be printed to the terminal in the appropriate color.

COLORNAMES_COLORS does not exist

In the README section titled Color palette, there is this example:

colorful.setup(colorpalette=colorful.COLORNAMES_COLORS))

Aside from the extra ) at the end of the line, the statement above produces an error: "the color "COLORNAMES" is unknown. Use a color in your color palette (by default: X11 rgb.txt)". Searching the code reveals that there is no symbol COLORNAMES_COLOR anywhere (except in the README.md text).

Nested placeholder remains in output

Describe the bug
We use colorful for coloring output for scripts started from Jenkins (using the https://github.com/jenkinsci/ansicolor-plugin plugin).
I'm not sure whether this is a bug or lack of support or both, but the effect is the following:
this line
logging.info(f"{colorful.bold_snow2(step.__name__)} starting")
produces the following ASCII output:
ESC[38;5;33m11:03:05ESC[0m ESC[38;5;68mINFOESC[0m ESC[38;5;75mworker_factory/mem:0B/473M/utime:0:ESC[0m ESC[38;5;253mESC[1mESC[38;5;231mDropNaESC[22mESC[39mESC[26m startingESC[0m
which is displayed in Jenkins output as (and you can see the output is truncated, instead of starting, there's sta:
image

It can be seen that an extra [26m (proportional spacing) is left, which can't be displayed (not supported?) by the Jenkins plugin. In the terminal this looks good.
After looking into colorful's code, I'm not sure if it's not a bug (the [26m is there is mark nested borders, but it's left there).

Environment and Version

  • OS (incl. terminal and shell used): ubuntu:bionic docker image
  • Python Version: 3.6.9
  • colorful Version: the screenshot is with 0.4.2, but in the terminal I've tried with 0.5.4 which seems to produce the same output.

To Reproduce
https://gist.github.com/bra-fsn/5f875a29bf043ae74748f2f9b2dbac81

Expected behavior
I'm not sure, but I guess that [26m shouldn't be there.

Use Python's curses module to use terminfo data

The Python curses module should be used to access the terminfo data for the currently used terminal. This allows us to support a wider range of terminals by using the ANSI escape sequences provided by the appropriate terminfo db.

However, terminfo does somehow not support true colors. It'll return 256 max_colors although most of the terminal emulators do support true colors ...

AttributeError: 'mod_wsgi.Log' object has no attribute 'encoding'

Hi,

i am using colorful as part of a custom library which also runs in a web application. We use mod_wsgi to serve the application and it seems that mod_wsgi replaces sys.stdout with a custom "Log"-object which doesn' t provide the "encoding" attribute.

I think this scenario happens quite frequently and i think that this should be handled cracefully in colorful.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.