Code Monkey home page Code Monkey logo

colr's Introduction

Colr

A python module for using terminal colors. It contains a simple color function that accepts style and color names, and outputs a string with escape codes, but also has all colors and styles as chainable methods on the Colr object.

See also: ColrC (Colr for C)


Dependencies:

System

Modules

There are no dependencies required for importing this library, however:

Installation:

Colr is listed on PyPi, and can be installed using pip:

pip install colr

Or you can clone the repo on GitHub and install it from the command line:

git clone https://github.com/welbornprod/colr.git
cd colr
python3 setup.py install

Examples:

Simple:

from colr import color
print(color('Hello world.', fore='red', style='bright'))

Chainable:

from colr import Colr as C
print(
    C()
    .bright().red('Hello ')
    .normal().blue('World')
)

# Background colors start with 'bg', and AttributeError will be raised on
# invalid method names.
print(C('Hello ', fore='red').bgwhite().blue('World'))

Examples (256 Colors):

Simple:

from colr import color
# Invalid color names/numbers raise a ValueError.
print(color('Hello world', fore=125, back=80))

Chainable:

from colr import Colr as C
# Foreground colors start with 'f_'
# Background colors start with 'b_'
print(C().f_125().b_80('Hello World'))

Examples (True Color):

Simple:

from colr import color
print(color('Hello there.', fore=(255, 0, 0), back=(0, 0, 0)))

Chainable:

from colr import Colr as C
# Foreground colors are set with the `rgb()` method.
# Background colors are set with the `b_rgb()` method.
# Text for the chained methods should be chained after or during
# the call to the methods.
print(C().b_rgb(0, 0, 0).rgb(255, 0, 0, 'Hello there.'))

Examples (Hex):

Simple:

from colr import color
# When not using the Colr.hex method, the closest matching extended code
# is used. For true color, just use:
#     fore=hex2rgb('ff0000')
# or
#     Colr.hex('ff0000', rgb_mode=True)
print(color('Hello there.', fore='ff0000', back='000'))

Chainable:

from colr import Colr as C
# Foreground colors are set with the `hex()` method.
# Background colors are set with the `b_hex()` method.
# Text for the chained methods should be chained after or during
# the call to the methods.
print(C().b_hex('#000').hex('ff0000', 'Hello there.'))

# With rgb_mode set, these are the same:
print(C().hex('ff0000', 'test', rgb_mode=True))
print(C().rgb(255, 0, 0, 'test'))

Documentation:

Documentation for the colr API can be found in the GitHub repo (github.com/welbornprod/colr):

Module/Object Description
colr.Colr Methods for the Colr object, to colorize text.
colr.Control Functions, classes, and methods for the Control object, to control the cursor/screen.
colr.ColrControl Colr and Control merged into one class. See colr.Colr and colr.Control.
colr.progress Progress updates, bars, or spinners.
colr.trans Color code translation/detection.

Colr Tool:

The colr package can be used as a command line tool. An entry point script named colr is created when installed with pip. Otherwise it can be executed using the python -m colr method.

colr --help

Basic usage involves passing text, or piping stdin data and setting the colors by position or flag.

# These all do the same thing:
colr "Test" "red" "white" "bright"
colr "Test" -f "red" -b "white" -s "bright"
printf "Test" | colr -f "red" -b "white" -s "bright"

Using the positional arguments is faster for just setting fore colors, but the flag method is needed for stdin data, or for picking just the background color or style:

colr "Test" -s "bright"

Extended and True colors are supported:

colr "Test" 124 255
colr "Test" "255, 0, 0" "255, 255, 255"
# Use true color (rgb) escape codes to generate a gradient, and then
# center it in the terminal (0 means use terminal width).
colr "Test" -G "255,0,0" -G "0,0,255" -c 0

It will do fore, back, style, gradients, rainbows, justification, and translation. It can strip codes from text (as an argument or stdin), or explain the codes found in the text.

lolcat emulation:

fortune | colr --rainbow

The colr tool does not read files, but it's not a problem:

cat myfile.txt | colr --gradient red

Also see ccat.

Colr-run:

A small command-runner is included, called colr-run. This program will run another program, printing an animated message instead of the normal output.

It is used to turn "noisy" commands into a nice single-line animation.

Basic Example:

To run a program with the default settings, -- is still required:

colr-run -- bash -c 'x=0; while ((x<1000000)); do let x+=1; done'

Any stderr output from the program will ruin the animation, which may be fine if you are only looking for errors.

You can silence stderr output with -e if you don't need it:

colr-run -e -- some-long-running-command

The exit status of colr-run is the exit status of the command being executed. For colr-run errors, the exit status is 1 for basic errors, and 2 for cancelled commands.

Colr.docopt:

Colr provides a wrapper for docopt that will automatically colorize usage strings. If you provide it a script name it will add a little more color by colorizing the script name too.

from colr import docopt
argd = docopt(USAGE, script='mycommand')

Contributing:

As always contributions are welcome here. If you think you can improve something, or have a good idea for a feature, please file an issue or a pull request.


Notes:

Reasons

In the past, I used a simple color() function because I'm not fond of the string concatenation style that other libraries use. The 'clor' javascript library uses method chaining because that style suits javascript, but I wanted to make it available to Python also, at least as an option.

Reset Codes

The reset code is appended only if some kind of text was given, and colr/style args were used. The only values that are considered 'no text' values are None and '' (empty string). str(val) is called on all other values, so Colr(0, 'red') and Colr(False, 'blue') will work, and the reset code will be appended.

This makes it possible to build background colors and styles, but also have separate styles for separate pieces of text.

Python 2

I don't really have the desire to back-port this to Python 2. It wouldn't need too many changes, but I like the Python 3 features (yield from, str/bytes).

Windows

Windows 10 finally has support for ANSI escape codes. Colr can now be used on Windows 10+ by calling SetConsoleMode. Older Windows versions are not supported and haven't been tested. If you are using Colr for a tool that needs to support older Windows versions, you will need to detect the current Windows version and call colr.disable() for those that aren't supported. Otherwise you will have "junk" characters printed to the screen.

Misc.

This library may be a little too flexible:

from colr import Colr as C


warnmsg = lambda s: C('warning', 'red').join('[', ']')(' ').green(s)
print(warnmsg('The roof is on fire again.'))

The possibilities are endless.

colr's People

Contributors

cjwelborn avatar jayvdb avatar sebleier 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

Watchers

 avatar  avatar  avatar  avatar  avatar

colr's Issues

doesnt work 2: electric boogalo

#4
windows 10 and debian linux

python 3.7

putty through ssh and whatever IDEa is.

256 color, true colors and hex examples in the readme.

doesnt work

text is completly normal, using multiple of the example methods

Custom method, __colr__, not documented.

Colr(obj), with no args, and where obj has a __colr__() method that returns a Colr object, will return obj.__colr__().

This is the Colr version of __str__ or __bytes__.

If you need your classes to colorize themselves a certain way by default, you can write a custom __colr__ method and Colr(mything) will recognize it. The quickest example is this:

from colr import Colr

class ErrorTag(object):

    def __str__(self):
        """ Stringify this thing. """
        return 'Error'
    
    def __colr__(self):
    """ Colrize this thing. """
        # must return a Colr instance.
        return Colr('Error', 'red', style='bright')

o = ErrorTag()
# prints a bright red 'Error'.
print(Colr(o))

None of this is documented, except here in this issue. It needs to be in the README.

Python 3.7 support

Tests fail on Python 3.7 : RuntimeError: generator raised StopIteration

Two failures on openSUSE

With the patch for #7 applied against the current release, I get the following two errors.

Maybe they have been fixed on master. I'll try that next..

[   67s] =================================== FAILURES ===================================
[   67s] ________________________ ColrToolTests.test_list_codes _________________________
[   67s] 
[   67s] self = <test.test_colr_tool.ColrToolTests testMethod=test_list_codes>
[   67s] 
[   67s]     def test_list_codes(self):
[   67s]         """ colr tool should list escape codes with --listcodes. """
[   67s]         cases = {
[   67s]             s: str(Colr('test', s))
[   67s]             for s in ('red', 'blue', 'green', 'white')
[   67s]         }
[   67s]         for name, s in cases.items():
[   67s]             argd = {'TEXT': s, '--listcodes': True}
[   67s]             self.assertMainIn(
[   67s]                 argd,
[   67s]                 stdout=name,
[   67s] >               msg='main() with --listcodes did not recognize an escape code.',
[   67s]             )
[   67s] 
[   67s] test/test_colr_tool.py:334: 
[   67s] _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
[   67s] test/testing_tools.py:694: in assertMainIn
[   67s]     msg='main() returned a non-zero exit status.',
[   67s] _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
[   67s] 
[   67s] self = <test.test_colr_tool.ColrToolTests testMethod=test_list_codes>, a = 1
[   67s] b = 0, msg = 'main() returned a non-zero exit status.'
[   67s] 
[   67s]     def assertEqual(self, a, b, msg=None):
[   67s]         if a == b:
[   67s]             return None
[   67s] >       raise self.failureException(_equality_msg('!=', a, b, msg=msg))
[   67s] E       AssertionError: 
[   67s] E         1 !=
[   67s] E         0
[   67s] E       
[   67s] E       main() returned a non-zero exit status.
[   67s] 
[   67s] test/testing_tools.py:417: AssertionError
[   67s] __________________________ ColrToolTests.test_styles ___________________________
[   67s] 
[   67s] self = <test.test_colr_tool.ColrToolTests testMethod=test_styles>
[   67s] 
[   67s]     def test_styles(self):
[   67s]         """ colr tool should recognize styles. """
[   67s]         argd = {'TEXT': 'Hello World', 'FORE': '235', 'STYLE': 'normal'}
[   67s]         for _ in range(10):
[   67s]             argd['STYLE'] = r.choice(self.valid_style_vals)
[   67s]             self.assertMain(argd, msg='main() failed with valid style arg.')
[   67s]         # Invalid style values should raise a InvalidStyle.
[   67s]         badargsets = (
[   67s]             {'STYLE': 'dimmer'},
[   67s]             {'STYLE': 'x'},
[   67s]         )
[   67s]         for argset in badargsets:
[   67s]             argd.update(argset)
[   67s]             with self.assertRaises(InvalidStyle):
[   67s] >               self.run_main_test(argd, should_fail=True)
[   67s] E               AssertionError: InvalidStyle not raised
[   67s] 
[   67s] test/test_colr_tool.py:427: AssertionError

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.