Giter Club home page Giter Club logo

clint's Introduction

Clint: Python Command-line Interface Tools

Clint is a module filled with a set of awesome tools for developing commandline applications.

https://raw.github.com/kennethreitz/clint/master/misc/clint.jpeg

C ommand L ine IN terface T ools .

Clint is awesome. Crazy awesome. It supports colors, but detects if the session is a TTY, so doesn't render the colors if you're piping stuff around. Automagically.

Awesome nest-able indentation context manager. Example: (with indent(4): puts('indented text')). It supports custom email-style quotes. Of course, it supports color too, if and when needed.

It has an awesome Column printer with optional auto-expanding columns. It detects how wide your current console is and adjusts accordingly. It wraps your words properly to fit the column size. With or without colors mixed in. All with a single function call.

The world's easiest to use implicit argument system w/ chaining methods for filtering. Seriously.

Run the various executables in examples to get a good feel for what Clint offers.

You'll never want to not use it.

https://travis-ci.org/kennethreitz/clint.png?branch=master

Current Features:

  • Little Documentation (bear with me for now)
  • CLI Colors and Indents
  • Extremely Simple + Powerful Column Printer
  • Iterator-based Progress Bar
  • Implicit Argument Handling
  • Simple Support for Incoming Unix Pipes
  • Application Directory management

Future Features:

  • Documentation!
  • Simple choice system Are you sure? [Yn]
  • Suggestions welcome.

Example

I want to indent my console text.

>>> from clint.textui import puts, indent

>>> puts('not indented text')
>>> with indent(4):
>>>     puts('indented text')
not indented text
    indented text

I want to quote my console text (like email).

>>> puts('not indented text')
>>> with indent(4, quote=' >'):
>>>     puts('quoted text')
>>>     puts('pretty cool, eh?')

not indented text
 >  quoted text
 >  pretty cool, eh?

I want to color my console text.

>>> from clint.textui import colored, puts

>>> puts(colored.red('red text'))
red text

# It's red in Windows, OSX, and Linux alike.

I want to get data piped to stdin.

>>> clint.piped_in()

# if no data was piped in, piped_in returns None

I want to get the first commandline argument passed in.

>>> from clint import arguments
>>> args = arguments.Args()
>>> args.get(0)

# if no argument was passed, get returns None

I want to store a configuration file.

>>> from clint import resources

>>> resources.init('Company', 'AppName')
>>> resources.user.write('config.ini', file_contents)

# OSX: '/Users/appuser/Library/Application Support/AppName/config.ini'
# Windows: 'C:\\Users\\appuser\\AppData\\Local\\Company\\AppName\\config.ini'
# Linux: '/home/appuser/.config/appname/config.ini'

I want to force color output even if stdout is not a TTY:

$ export CLINT_FORCE_COLOR=1

I want to ask for input.

>>> from clint.textui import prompt, validators
>>> path = prompt.query('Installation Path', default='/usr/local/bin/', validators=[validators.PathValidator()])

Installation

To install clint, simply:

$ pip install clint

Or, if you absolutely must:

$ easy_install clint

But, you really shouldn't do that.

License:

ISC License.

Copyright (c) 2011, Kenneth Reitz <[email protected]>

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Contribute

If you'd like to contribute, simply fork the repository, commit your changes to the master branch (or branch off of it), and send a pull request. Make sure you add yourself to AUTHORS.

Roadmap

  • Unittests
  • Sphinx Documentation

clint's People

Contributors

ashleyh avatar barberj avatar brandly avatar branliu0 avatar collinwat avatar davefnbuck avatar ewa avatar futoase avatar graingert avatar haqthat avatar hickford avatar hvnsweeting avatar infamy avatar jpiper avatar kennethreitz avatar kracekumar avatar lothiraldan avatar maraujop avatar mccartney avatar mjs2600 avatar saimn avatar sebix avatar sghill avatar takluyver avatar techniq avatar techtonik avatar teh avatar thusoy avatar waldyrious avatar wkentaro 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

Watchers

 avatar  avatar  avatar  avatar

clint's Issues

Import error in examples/progressbar.py

$ ./examples/progressbar.py 

Traceback (most recent call last):
  File "/home/jhosang/src/clint/examples/progressbar.py", line 11, in <module>
    from clint.textui import progressbar
ImportError: cannot import name progressbar

Following import fixes it for me:
from clint.textui.progress import bar as progressbar

Current repo is broken? (2012 Nov 15)

After running into the broken colour on Windows problem which is apparently fixed in code but not in the current release (#75) I thought I'd download what is current from github (https://github.com/kennethreitz/clint/archive/develop.zip), but that seems to be broken completely:

B:\code\clint>python setup.py
Traceback (most recent call last):
  File "setup.py", line 12, in <module>
    import clint
  File "B:\code\clint\clint\__init__.py", line 21, in <module>
    from arguments import *
ImportError: No module named arguments

And it appears I'm not the only one, https://readthedocs.org/projects/clint/ says the builds have been failing for the last 7 weeks with a similar error:

Exception occurred:
  File "/var/build/user_builds/clint/checkouts/latest/clint/__init__.py", line 21, in <module>
    from arguments import *
ImportError: No module named arguments

/examples/args.sh fails

root@box:/tmp/clint/examples# ./args.sh

No arguments:
Traceback (most recent call last):
File "args.py", line 9, in
from clint import args
ImportError: cannot import name args
A few arguments:
Traceback (most recent call last):
File "args.py", line 9, in
from clint import args
ImportError: cannot import name args
A few expanded file arguments:
Traceback (most recent call last):
File "args.py", line 9, in
from clint import args
ImportError: cannot import name args
A few non-expanded file arguments:
Traceback (most recent call last):
File "args.py", line 9, in
from clint import args
ImportError: cannot import name args
A few mixed files/flags/arguments:
Traceback (most recent call last):
File "args.py", line 9, in
from clint import args
ImportError: cannot import name args

clint fails to install with easy_install

$ easy_install clint
Searching for clint
Reading http://pypi.python.org/simple/clint/
No local packages or download links found for clint
Best match: None
Traceback (most recent call last):
File "/home/trey/repos/python/pep438/test/bin/easy_install", line 8, in <module>
    load_entry_point('setuptools==0.6c11', 'console_scripts', 'easy_install')()
File "/home/trey/repos/python/pep438/test/local/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 1712, in main
File "/home/trey/repos/python/pep438/test/local/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 1700, in with_ei_usage
File "/home/trey/repos/python/pep438/test/local/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 1716, in <lambda>
File "/usr/lib/python2.7/distutils/core.py", line 152, in setup
    dist.run_commands()
File "/usr/lib/python2.7/distutils/dist.py", line 953, in run_commands
    self.run_command(cmd)
File "/usr/lib/python2.7/distutils/dist.py", line 972, in run_command
    cmd_obj.run()
File "/home/trey/repos/python/pep438/test/local/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 211, in run
File "/home/trey/repos/python/pep438/test/local/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/command/easy_install.py", line 434, in easy_install
File "/home/trey/repos/python/pep438/test/local/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg/setuptools/package_index.py", line 475, in fetch_distribution
AttributeError: 'NoneType' object has no attribute 'clone'

This is causing coverage run setup.py test to fail for pep438 which stops the Travis tests from passing.

py3 support problem in progress

careful with py3 division.

$ python3.4 progressbar.py
[################################] 100/100 - 00:00:00
nonlinear[################################] 10/10 - 00:00:00
....................................................................................................
Traceback (most recent call last):
  File "progressbar.py", line 28, in <module>
    for i in progress.mill(range(100)):
  File "/usr/local/lib/python3.4/site-packages/clint/textui/progress.py", line 152, in mill
    _show(0)
  File "/usr/local/lib/python3.4/site-packages/clint/textui/progress.py", line 146, in _show
    label, _mill_char(_i), _i, count))
  File "/usr/local/lib/python3.4/site-packages/clint/textui/progress.py", line 138, in _mill_char
    return MILL_CHARS[(_i / every) % len(MILL_CHARS)]
TypeError: list indices must be integers, not float

An efficiency improvement recommendations

in file clint/utils.py

tsplit and schunk are inefficient for many temp str(PyStringObject) instance

my suggestion is


def tsplit2(string, delimiters):
    delimiters = tuple(delimiters)
    if len(delimiters) < 1:
        return [string,]
    final_delimiter = delimiters[0]
    for i in delimiters[1:]:
        string = string.replace(i, final_delimiter)
    return string.split(final_delimiter)

def schunk2(string, size):
    return [string[i:i+size] for i in range(0, len(string), size)]

and tsplit only use like this : tsplit(string, NEW_LINE), why not use string.splitlines()

clint.resources.bundler

Possibly add bundler functionality that would allow you to serialize/deserialize an chunk of application data for freezing.

rjust and ljust has wrong offset

>>> print "{}".format(colored.red("hello")).rjust(12)
hello
>>> print "{}".format(colored.red("hello")).rjust(20)
     hello
>>> print "{}".format("hello").rjust(20)
               hello

handling arg flags with options followed by non-options

Can clint handle arguments with options (flags) followed by something else not related to the option? If so, how?

Many existing programs operating in the environment where I'm creating my program in use the patterns below, all of which are functionally identical.

bazwarp --target-size 1024 768 --resample=cubic input.jpg output.jpg
bazwarp --resample cubic input.jpg output.jpg --target-size 1024 768 
bazwarp -r cubic input.jpg -ts 1024 768 output.jpg
bazwarp input.jpg output.jpg --target-size 1024 768 --resample cubic 

Following clint\example\args.py, it looks like only the last of these would be grouped by correctly* by clint, right? (Where "correctly" means I would only have to have to write one code block to handle each parameter or group, and those blocks would handle all four variants (thought admittedly sprinkling the in/out files among the flags in the 3rd example a bit contrived)).

Percentage In Progress Bar

Would you be willing to accept a patch replacing

BAR_TEMPLATE = '%s[%s%s] %i/%i - %s\r'

with

BAR_TEMPLATE = '%s[%s%s] %i\% - %s\r'

So that

[################################] 3728/3728 - 00:00:00

becomes

 [################################] 100% - 00:00:00

?

0.3.2 release

I personnaly need some news features of clint in one of my project and wait for a new release of clint in order to release it. Is it planned for soon?

256-color terminal support

Very nice project, I've been pondering abut something like this for a while, and existing Python console support projects seem to have died a quiet death.

A small feature request: Most terminals these days support 256 color (gnome, konsole, even old xterm/mrxvt). It'd be awesome if you could use these colors in Clint (for example, by setting colors as RGB and choosing the closest color). We're now in 2011 and 8-color text is old-fashioned :)

I might get around to implementing this myself and submitting a patch. I have code for this in one of my other projects. (As for lists of R/G/B values, and/or color names, IPython could be an inspiration as it has a module for it)

textui.auto_columns

>>> auto_columns(list_of_strings)
# prints strings in appropriate columns, like `ls`

>>> auto_columns(list_of_strings, 10)
# prints strings in columns with a width of 10

README and HISTORY installed to /usr

I ran sudo pip install clint and...

Installing collected packages: clint
  Running setup.py install for clint
    warning: install_data: setup script did not provide a directory for 'README.rst' -- installing right in '/usr'
    warning: install_data: setup script did not provide a directory for 'HISTORY.rst' -- installing right in '/usr'

Python 3.2.2

PyPi package

Is the PyPi package (clint2 0.3.2 or clint 0.3.1) up to date? Neither package supports the expected_size arg in textui.progress.bar, though it appears to be in the current version of the code.

Typo in readme example

The example with colored console text ("I want to color my console text. ...") forgets to import puts.

from clint.textui import colored
should be
from clint.textui import colored, puts

OTOH, if making the assumption that the user is typing all examples in sequentially and it's acceptable for them to be incomplete, I think this should be made more explicit to prevent confusion.

clint.eng module

Join:

>>> clint.eng.join(['blue', 'red', 'yellow'])
blue, red, and yellow

>>> clint.eng.join(['blue', 'red', conj='or']
blue or red

>>> clint.eng.join(['blue']
blue

Secret feature! Non-oxford comas!

>>> clint.eng.join(['blue', 'red', 'yellow'], im_a_moron=True)
blue, red and yellow

Plural:

>>>> shelf = Shoe()
>>> clint.plural('shoe', shelf)
# calls __len__ on shoe?
shoe


>>>> shelf = [Shoe(), Shoe()]
>>> clint.plural.eng('shoe', shelf)
# implied 's' plural
shoes


>>>> shelf = [Octopus(), Octopus()]
>>> clint.eng.plural('octopus', shelf, plural='octopi')
octopi

Maye support for __plural__ method?

Show details during a progress

With the progress module, if you print information about the data in treatment, the progress bar is broken.
Example:

for i in progress.bar(range(100)):
    print(i)
    sleep(random() * 0.2)

It could be useful to add a method to print the current data processed, under the progress bar for example:

for i in progress.bar(range(100)):
    progress.details(i)
    sleep(random() * 0.2)

Windows colored text is not working

I have tried the all_colors.py example code on both Windows XP and Windows 7, using Python 3.2.2, and the output is surrounded by ANSI escape sequences, but it is not actually colored. It looks like the ANSI interpereter is not running in Windows. Someone else tested in Linux and it worked correctly.

data files installed in the wrong location

The fix for issue 22 introduced a new problem. The data files are now installed in the top folder of the environment.

To reproduce do:

$ virtualenv-2.6 --distribute venv
New python executable in venv/bin/python2.6
...
$ cd venv/
$ bin/pip install clint
Downloading/unpacking clint
  Running setup.py egg_info for package clint
Installing collected packages: clint
  Running setup.py install for clint
    warning: install_data: setup script did not provide a directory for 'README.rst' -- installing right in '/opt/tmp/venv'
    warning: install_data: setup script did not provide a directory for 'HISTORY.rst' -- installing right in '/opt/tmp/venv'
Successfully installed clint
Cleaning up...
$ ls
HISTORY.rst README.rst  bin     include     lib

distutils even warns about this. In my case my own readme/history files are overwritten by this.

I think to solve the issue you had, you just want to use a MANIFEST.in which will tell distutils to include the files in the sdist. There's no need to actually install them on the target system. If you want to install them as well, I'd use setuptools/distribute include_package_data option (http://packages.python.org/distribute/setuptools.html#including-data-files).

IPython loses completion.

If I open up IPython and import clint (or a submodule), completion stops working;
e.g. if I press the 'up' button, it prints '^[[A' ; 'tab' inserts an actual tab.

Colored output combined with `input` and `raw_input`

Hi Kenneth,

I love this module for coloring the output to my terminal, it's fantastic. However, I have a script which requires user input via either input or raw_input something like this

na = raw_input("What is your name > ")

Here I would like to color name yellow. Is there a (simple) way to do that? My current workaround is

puts("What is your "+colored.yellow("name"))
na = raw_input("> ")

but this is obviosly written in two lines instead of one which I prefer.

Cheers,
Daniel

The tarball on pypi is not 0.3.5

Looks like a 0.3.3 release and not a 0.3.5: when I install clint from pip, the Bar context manager is not available (not in the code).

Purge arguments/args code from clint

Following on from ab401e7 arguments/args has been partially pulled out of clint, but there are still references to it.

Since there is the separate module https://github.com/kennethreitz/args the use of clint.args should be deprecated (but still backwards compatible, for a period of time). A corollary of this is that the examples directory should no longer demonstrate the features of the args module (but it's fine to use it in the demonstration of other things, such as in examples/unicode.py

Small import bug in __init__.py

Here's the fix diff :

--- a/clint/init.py
+++ b/clint/init.py
@@ -18,7 +18,7 @@ except ImportError:
import collections
collections.OrderedDict = OrderedDict

-from arguments import *
+from .arguments import *
from . import textui
from . import utils
from .pipes import piped_in

Merging with CLIZE ?

Clint is in a on it's way to join request and envoy in the VIP room for awsome Python API.

However, the way it handles arguments is limited.

There are ways to make handling arguments easy and clean, but still powerful.

What about something like clize ?

http://pypi.python.org/pypi/clize/1.0b

Hide progress after end

It would be nice to have a way to "hide" the progress message when it's finished, but show it while it's being completed (right now it's all-or-nothing).

Writer converts everything to str

The Writer class converts all strings to str. This causes Problems with unicode strings.

64     def __call__(self, s, newline=True, stream=STDOUT):
65 
66         if newline:
67             s = tsplit(s, NEWLINES)
68             s = map(str, s)
69             indent = ''.join(self.shared['indent_strings'])
70 
71             s = (str('\n' + indent)).join(s)
72 
73         _str = ''.join((
74             ''.join(self.shared['indent_strings']),
75             str(s),
76             '\n' if newline else ''
77         ))
78         stream(_str)

While I can print a unicode string

>>> print u'äöü'
äöü

...I cannot do that when using puts.

>>> puts(u'äöü')
Traceback (most recent call last):
  File "test.py", line 7, in <module>
    puts(u'äöü')
  File "/home/danilo/Projects/clint/clint/textui/core.py", line 83, in puts
    Writer()(s, newline, stream=stream)
  File "/home/danilo/Projects/clint/clint/textui/core.py", line 68, in __call__
    s = map(str, s)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

This breaks puts-ing any non-ascii characters, which is a big problem for me.

This is probably the reason for #47.

examples/text_width.py only works with terminals wider than 135 chars

When running examples/text_width.py inside terminals with 135 or less characters in width, the following error pops up:

Traceback (most recent call last):
  File "text_width.py", line 22, in <module>
    puts(columns([(colored.red('Column 1')), col], [(colored.green('Column Two')), None], [(colored.magenta('Column III')), col]))
  File "/tmp/clint/clint/textui/cols.py", line 95, in columns
    cols[_big_col][0] = max_width(cols[_big_col][0], cols[_big_col][1]).split('\n')
  File "/tmp/clint/clint/textui/formatters.py", line 70, in max_width
    chunks = schunk(word, (cols + offset))
  File "/tmp/clint/clint/utils.py", line 61, in schunk
    for char in string:
TypeError: 'ColoredString' object is not iterable

"TypeError: coercing to Unicode" with colored output

A minor bug, but was confusing when I stumbled across it. puts(colored.red(1)) works as expected normally, but doesn't degrade correctly when colors aren't supported.

test1.py:

from clint.textui import puts, colored
puts(colored.red(1))

test2.py:

from clint.textui import puts, colored
puts(colored.red('1'))
$ python test1.py
1 (colored)
$ python test1.py | cat
TypeError: coercing to Unicode: need string or buffer, int found
$ python test2.py
1 (colored)
$ python test2.py | cat
1

columns + unicode

>>> puts(columns(['Star ★', 10]))
Star       
>>> puts(columns([colored.yellow('Star ★'), 10]))
Star ★

Indent/color context operators

This would be epic:

from clint.textui import colored, indent, puts

with indent(4):
    puts('something')
    puts('something:' +  colored.red('red'))
    with indent(2):
        puts('yet something else')


with colored.blue:
    puts('this is blue')

Add a .travis.yml in order to enable CI

I would have done it myself but there is no documentation on how to write the tests or what versions of Python are supported.
Could you please add a .travis.yml?

color broken on Windows?

Hi, brand spankin new clint user here. Win7 pro x64, 32bit python 2.7.

I just installed clint with pip and tried the args.py example and I get ansi escape characters instead of color. Am I missing some pre-requsite?

example cmd:

python -c "from clint.textui import colored, puts_err; puts_err(colored.red('red?'))"

emits:

←[31mred?←[39m

All examples not using color work. I'm running from a CMD shell. Any idea what's missing on my system?

thanks

clint breaks readline completion

importing clint breaks readline completion for raw_input. The following small example illustrates that behaviour:

#!/usr/bin/env python

#from clint import resources
import readline


def complete(text, state):
    if text[state].startswith('h'):
        return 'hello'
    return None

readline.parse_and_bind('tab: complete')
readline.set_completer(complete)

print raw_input('Tell me something: ')

if the clint import is uncommented the tab completion stops working.

cut a 0.3.7 release?

Would love to see a new version on pypi that includes the CLINT_FORCE_COLOR env var feature.

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.