Skip to content
Myr

Implemented and exposed click.echo

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 3f695c6 · Browse files · 14 files+84 added−58 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

14 files+84 added−58 removed

  • other:+84 added−58 removed

14 files+84 added−58 removed

modified:click/__init__.py+2 added-2 removed
25 unmodified lines
26# Types27from .types import ParamType, File, Choice, STRING, INT, FLOAT, BOOL2829# Helper functions30from .helpers import prompt, confirm, get_terminal_size30from .helpers import prompt, confirm, get_terminal_size, echo3132# Exceptions33from .exceptions import UsageError, Abort34
11 unmodified lines
46 # Types47 'ParamType', 'File', 'Choice', 'STRING', 'INT', 'FLOAT', 'BOOL',4849 # Helper functions50 'prompt', 'confirm', 'get_terminal_size',50 'prompt', 'confirm', 'get_terminal_size', 'echo',5152 # Exceptions53 'UsageError', 'Abort',54]
modified:click/core.py+2 added-2 removed
2 unmodified lines
3import codecs4from itertools import chain56from .types import convert_type, BOOL7from .utils import echo, make_str7from .utils import make_str8from .exceptions import UsageError, Abort9from .helpers import prompt, confirm9from .helpers import prompt, confirm, echo1011from . import _optparse12from ._compat import PY213
890 unmodified lines
modified:click/decorators.py+1 added-1 removed
1import inspect23from functools import update_wrapper45from .utils import echo5from .helpers import echo678def pass_context(f):9 """Marks a callback that it wants to receive the current context
249 unmodified lines
modified:click/helpers.py+22 added-2 removed
1import os2import sys3import struct45from ._compat import raw_input6from .utils import echo5from ._compat import raw_input, PY2, text_type6from .utils import get_best_encoding7from .exceptions import Abort, UsageError8from .types import convert_type910
137 unmodified lines
148 if not cr:149 cr = (os.environ.get('LINES', 25),150 os.environ.get('COLUMNS', 80))151 return int(cr[1]), int(cr[0])152153154def echo(message=None, file=None):155 """Prints a message plus a newline to the given file or stdout. On156 first sight this looks like the print function but it has improved157 support for handling unicode data that does not fail no matter how158 badly configured the system is.159160 :param message: the message to print161 :param file: the file to write to (defaults to ``stdout``)162 """163 if file is None:164 file = sys.stdout165 if message:166 if PY2 and isinstance(message, text_type):167 encoding = get_best_encoding(file)168 message = message.encode(encoding, 'replace')169 file.write(message)170 file.write('\n')171 file.flush()
modified:click/utils.py-13 removed
28 unmodified lines
29 return 'utf-8'30 return enc313233def echo(message=None, file=None):34 """Prints a message to the given file or stdout."""35 if file is None:36 file = sys.stdout37 if message:38 if PY2 and isinstance(message, text_type):39 encoding = get_best_encoding(file)40 message = message.encode(encoding, 'replace')41 file.write(message)42 file.write('\n')43 file.flush()444533def make_str(value):34 """Converts a value into a valid string."""35 if isinstance(value, bytes):36 try:
4 unmodified lines
modified:docs/api.rst+2 added
32 unmodified lines
3334Helper Functions35----------------3637.. autofunction:: echo3839.. autofunction:: prompt4041.. autofunction:: confirm42
56 unmodified lines
modified:docs/arguments.rst+3 added-3 removed
20 unmodified lines
2122 @click.command()23 @click.argument('filename')24 def touch(filename):25 print(filename)25 click.echo(filename)2627And what it looks like:2829.. click:run::
18 unmodified lines
48 @click.command()49 @click.argument('files', nargs=-1)50 def touch(files):51 for file in files:52 print(file)52 click.echo(file)5354And what it looks like:5556.. click:run::
50 unmodified lines
107108 @click.command()109 @click.argument('src', envvar='SRC', type=click.File('r'))110 def echo(src):111 print(src.read())111 click.echo(src.read())112113And from the command line:114115.. click:run::
11 unmodified lines
modified:docs/commands.rst+6 added-6 removed
23 unmodified lines
2425 @click.group()26 @click.option('--debug/--no-debug', default=False)27 def cli(debug):28 print('Debug mode is %s' % ('on' if debug else 'off'))28 click.echo('Debug mode is %s' % ('on' if debug else 'off'))2930 @cli.command()31 def sync():32 print('Synching')32 click.echo('Synching')3334Here is what this looks like:3536.. click:run::
34 unmodified lines
7172 @cli.command()73 @click.pass_context74 def sync(ctx):75 print('Debug is %s' % (ctx.obj['DEBUG'] and 'on' or 'off'))75 click.echo('Debug is %s' % (ctx.obj['DEBUG'] and 'on' or 'off'))7677 if __name__ == '__main__':78 cli(obj={})79
59 unmodified lines
139 @click.group(invoke_without_command=True)140 @click.pass_context141 def cli(ctx):142 if ctx.invoked_subcommand is None:143 print('I was invoked without subcommand')143 click.echo('I was invoked without subcommand')144 else:145 print('I am about to invoke %s' % ctx.invoked_subcommand)145 click.echo('I am about to invoke %s' % ctx.invoked_subcommand)146147 @cli.command()148 def sync():149 print('The subcommand')149 click.echo('The subcommand')150151And how it works in practice::152153 $ python tool.py
103 unmodified lines
modified:docs/documentation.rst+2 added-2 removed
19 unmodified lines
20 @click.argument('name')21 def hello(count, name):22 """This script prints hello NAME COUNT times."""23 for x in range(count):24 print('Hello %s!' % name)24 click.echo('Hello %s!' % name)2526And what it looks like:2728.. click:run::
21 unmodified lines
50 @click.argument('name', metavar='<name>')51 def hello(count, name):52 """This script prints hello <name> <int> times."""53 for x in range(count):54 print('Hello %s!' % name)54 click.echo('Hello %s!' % name)5556Example:5758.. click:run::
30 unmodified lines
modified:docs/index.rst+1 added-1 removed
25 unmodified lines
26 @click.option('--name', prompt='Your name',27 help='the person to greet', required=True)28 def hello(count, name):29 for x in range(count):30 print('Hello %s!' % name)30 click.echo('Hello %s!' % name)3132 if __name__ == '__main__':33 hello()34
36 unmodified lines
modified:docs/options.rst+18 added-18 removed
18 unmodified lines
1920 @click.command()21 @click.option('--n', default=1)22 def dots(n):23 print('.' * n)23 click.echo('.' * n)2425And on the command line:2627.. click:run::
14 unmodified lines
4243 @click.command()44 @click.option('--pos', nargs=2, type=float)45 def findme(pos):46 print('%s / %s' % pos)46 click.echo('%s / %s' % pos)4748And on the command line:4950.. click:run::
15 unmodified lines
6667 @click.command()68 @click.option('--message', '-m', multiple=True)69 def commit(message):70 print('\n'.join(message))70 click.echo('\n'.join(message))7172And on the command line:7374.. click:run::
13 unmodified lines
88 @click.command()89 @click.option('-v', '--verbose', is_flag=True, multiple=True)90 def log(verbose):91 verbosity = len(verbose)92 print('Verbosity: %s' % verbosity)92 click.echo('Verbosity: %s' % verbosity)9394And on the command line:9596.. click:run::
19 unmodified lines
116 def info(shout):117 rv = os.uname()[0]118 if shout:119 rv = rv.upper() + '!!!!111'120 print(rv)120 click.echo(rv)121122And on the command line:123124.. click:run::
13 unmodified lines
138 def info(shout):139 rv = os.uname()[0]140 if shout:141 rv = rv.upper() + '!!!!111'142 print(rv)142 click.echo(rv)143144And on the command line:145146.. click:run::
16 unmodified lines
163 @click.option('--upper', 'transformation', flag_value='upper',164 default=True)165 @click.option('--lower', 'transformation', flag_value='lower')166 def info(transformation):167 print(getattr(os.uname()[0], transformation)())167 click.echo(getattr(os.uname()[0], transformation)())168169And on the command line:170171.. click:run::
17 unmodified lines
189190 @click.command()191 @click.option('--hash-type', type=click.Choice(['md5', 'sha1']))192 def digest(hash_type):193 print(hash_type)193 click.echo(hash_type)194195What it looks like:196197.. click:run::
19 unmodified lines
217218 @click.command()219 @click.option('--name', prompt=True)220 def hello(name):221 print('Hello %s!' % name)221 click.echo('Hello %s!' % name)222223And what it looks like:224225.. click:run::
8 unmodified lines
234235 @click.command()236 @click.option('--name', prompt='Your name please')237 def hello(name):238 print('Hello %s!' % name)238 click.echo('Hello %s!' % name)239240What it looks like:241242.. click:run::
11 unmodified lines
254 @click.command()255 @click.option('--password', prompt=True, hide_input=True,256 confirmation_prompt=True)257 def encrypt(password):258 print('Encrypting password to %s' % password.encode('rot13'))258 click.echo('Encrypting password to %s' % password.encode('rot13'))259260What it looks like:261262.. click:run::
7 unmodified lines
270271 @click.command()272 @click.password_option()273 def encrypt(password):274 print('Encrypting password to %s' % password.encode('rot13'))274 click.echo('Encrypting password to %s' % password.encode('rot13'))275276Callbacks and Eager Options277---------------------------278
20 unmodified lines
299300 def print_version(ctx, value):301 if not value:302 return303 print('Version 1.0')303 click.echo('Version 1.0')304 ctx.exit()305306 @click.command()307 @click.option('--version', is_flag=True, callback=print_version,308 expose_value=False, is_eager=True)309 def hello():310 print('Hello World!')310 click.echo('Hello World!')311312The `expose_value` parameter prevents the now pretty pointless ``version``313parameter to be passed to the callback. If that was not specified a314boolean would be passed to the `hello` script.
23 unmodified lines
338 @click.option('--yes', is_flag=True, callback=abort_if_false,339 expose_value=False,340 prompt='Are you sure you want to drop the db?')341 def dropdb():342 print('Dropped all tables!')342 click.echo('Dropped all tables!')343344And what it looks like on the command line:345346.. click:run::
8 unmodified lines
355356 @click.command()357 @click.confirmation_option('Are you sure you want to drop the db?')358 def dropdb():359 print('Dropped all tables!')359 click.echo('Dropped all tables!')360361Values from Environment Variables362---------------------------------363
18 unmodified lines
382383 @click.command()384 @click.option('--username')385 def greet(username):386 print('Hello %s!' % username)386 click.echo('Hello %s!' % username)387388 if __name__ == '__main__':389 greet(auto_envvar_prefix='GREETER')390
13 unmodified lines
404405 @click.command()406 @click.option('--username', envvar='USERNAME')407 def greet(username):408 print('Hello %s!' % username)408 click.echo('Hello %s!' % username)409410 if __name__ == '__main__':411 greet()412
8 unmodified lines
modified:docs/prompts.rst+1 added-1 removed
38 unmodified lines
39function comes in handy. By default it returns the result of the prompt40as boolean value::4142 if click.confirm('Do you want to continue?'):43 print('Well done!')43 click.echo('Well done!')4445There is also the option to make it automatically abort the execution::4647 click.confirm('Do you want to continue?', abort=True)
modified:docs/quickstart.rst+23 added-6 removed
22 unmodified lines
23 import click2425 @click.command()26 def hello():27 print('Hello World!')27 click.echo('Hello World!')2829What's happening is that the decorator converts the function into a30:class:`Command` which then can be invoked::31
11 unmodified lines
43.. click:run::4445 invoke(hello, args=['--help'])4647Echoing48-------4950Why does this example use :func:`echo` instead of the regular51:func:`print` function? The answer to this question is that click52attempts to support both Python 2 and Python 3 the same way and to be very53robust even when the environment is misconfigured. Click wants to be54functional at least on a basic level even if everything is completely55broken.5657What this means is that the :func:`echo` function applies some error58correction in case the terminal is misconfigured instead of dying with an59:exc:`UnicodeError`.6061If you don't need this, you can also use the `print()` construct /62function.6364Nesting Commands65----------------6667Commands can be attached to other commands of type :class:`Group`. This
7 unmodified lines
75 pass7677 @click.command()78 def initdb():62 print('Initialized the database')79 click.echo('Initialized the database')8081 @click.command()82 def dropdb():66 print('Dropped the database')83 click.echo('Dropped the database')8485 cli.add_command(initdb)86 cli.add_command(dropdb)87
13 unmodified lines
101 pass102103 @cli.command()104 def initdb():88 print('Initialized the database')105 click.echo('Initialized the database')106107 @cli.command()108 def dropdb():92 print('Dropped the database')109 click.echo('Dropped the database')110111Adding Parameters112-----------------113
5 unmodified lines
119 @click.option('--count', default=1, help='number of greetings')120 @click.argument('name')121 def hello(count, name):122 for x in range(count):106 print('Hello %s!' % name)123 click.echo('Hello %s!' % name)124125What it looks like:126127.. click:run::
2 unmodified lines
modified:docs/setuptools.rst+1 added-1 removed
32 unmodified lines
3334 @click.command()35 def cli():36 """Example script."""37 print('Hello World!')37 click.echo('Hello World!')3839Contents of ``setup.py``::4041 from setuptools import setup, find_packages
38 unmodified lines