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
Provenance
- Commit
95c24b3- Tree
6065c92- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
3f695c6
14 files changed+84 added−58 removed
modified:click/__init__.py+2 added-2 removed
25 unmodified lines26 # Types27 from .types import ParamType, File, Choice, STRING, INT, FLOAT, BOOL28 29 # Helper functions30-from .helpers import prompt, confirm, get_terminal_size30+from .helpers import prompt, confirm, get_terminal_size, echo31 32 # Exceptions33 from .exceptions import UsageError, Abort34 11 unmodified lines46 # Types47 'ParamType', 'File', 'Choice', 'STRING', 'INT', 'FLOAT', 'BOOL',48 49 # Helper functions50- 'prompt', 'confirm', 'get_terminal_size',50+ 'prompt', 'confirm', 'get_terminal_size', 'echo',51 52 # Exceptions53 'UsageError', 'Abort',54 ]modified:click/core.py+2 added-2 removed
2 unmodified lines3 import codecs4 from itertools import chain5 6 from .types import convert_type, BOOL7-from .utils import echo, make_str7+from .utils import make_str8 from .exceptions import UsageError, Abort9-from .helpers import prompt, confirm9+from .helpers import prompt, confirm, echo10 11 from . import _optparse12 from ._compat import PY213 890 unmodified linesmodified:click/decorators.py+1 added-1 removed
1 import inspect2 3 from functools import update_wrapper4 5-from .utils import echo5+from .helpers import echo6 7 8 def pass_context(f):9 """Marks a callback that it wants to receive the current context249 unmodified linesmodified:click/helpers.py+22 added-2 removed
1 import os2 import sys3 import struct4 5-from ._compat import raw_input6-from .utils import echo5+from ._compat import raw_input, PY2, text_type6+from .utils import get_best_encoding7 from .exceptions import Abort, UsageError8 from .types import convert_type9 10 137 unmodified lines148 if not cr:149 cr = (os.environ.get('LINES', 25),150 os.environ.get('COLUMNS', 80))151 return int(cr[1]), int(cr[0])152+153+154+def 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.159+160+ :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 lines29 return 'utf-8'30 return enc31 32 33-def 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()44-45-33 def make_str(value):34 """Converts a value into a valid string."""35 if isinstance(value, bytes):36 try:4 unmodified linesmodified:docs/api.rst+2 added
32 unmodified lines33 34 Helper Functions35 ----------------36 37+.. autofunction:: echo38+39 .. autofunction:: prompt40 41 .. autofunction:: confirm42 56 unmodified linesmodified:docs/arguments.rst+3 added-3 removed
20 unmodified lines21 22 @click.command()23 @click.argument('filename')24 def touch(filename):25- print(filename)25+ click.echo(filename)26 27 And what it looks like:28 29 .. click:run::18 unmodified lines48 @click.command()49 @click.argument('files', nargs=-1)50 def touch(files):51 for file in files:52- print(file)52+ click.echo(file)53 54 And what it looks like:55 56 .. click:run::50 unmodified lines107 108 @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())112 113 And from the command line:114 115 .. click:run::11 unmodified linesmodified:docs/commands.rst+6 added-6 removed
23 unmodified lines24 25 @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'))29 30 @cli.command()31 def sync():32- print('Synching')32+ click.echo('Synching')33 34 Here is what this looks like:35 36 .. click:run::34 unmodified lines71 72 @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'))76 77 if __name__ == '__main__':78 cli(obj={})79 59 unmodified lines139 @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)146 147 @cli.command()148 def sync():149- print('The subcommand')149+ click.echo('The subcommand')150 151 And how it works in practice::152 153 $ python tool.py 103 unmodified linesmodified:docs/documentation.rst+2 added-2 removed
19 unmodified lines20 @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)25 26 And what it looks like:27 28 .. click:run::21 unmodified lines50 @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)55 56 Example:57 58 .. click:run::30 unmodified linesmodified:docs/index.rst+1 added-1 removed
25 unmodified lines26 @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)31 32 if __name__ == '__main__':33 hello()34 36 unmodified linesmodified:docs/options.rst+18 added-18 removed
18 unmodified lines19 20 @click.command()21 @click.option('--n', default=1)22 def dots(n):23- print('.' * n)23+ click.echo('.' * n)24 25 And on the command line:26 27 .. click:run::14 unmodified lines42 43 @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)47 48 And on the command line:49 50 .. click:run::15 unmodified lines66 67 @click.command()68 @click.option('--message', '-m', multiple=True)69 def commit(message):70- print('\n'.join(message))70+ click.echo('\n'.join(message))71 72 And on the command line:73 74 .. click:run::13 unmodified lines88 @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)93 94 And on the command line:95 96 .. click:run::19 unmodified lines116 def info(shout):117 rv = os.uname()[0]118 if shout:119 rv = rv.upper() + '!!!!111'120- print(rv)120+ click.echo(rv)121 122 And on the command line:123 124 .. click:run::13 unmodified lines138 def info(shout):139 rv = os.uname()[0]140 if shout:141 rv = rv.upper() + '!!!!111'142- print(rv)142+ click.echo(rv)143 144 And on the command line:145 146 .. click:run::16 unmodified lines163 @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)())168 169 And on the command line:170 171 .. click:run::17 unmodified lines189 190 @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)194 195 What it looks like:196 197 .. click:run::19 unmodified lines217 218 @click.command()219 @click.option('--name', prompt=True)220 def hello(name):221- print('Hello %s!' % name)221+ click.echo('Hello %s!' % name)222 223 And what it looks like:224 225 .. click:run::8 unmodified lines234 235 @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)239 240 What it looks like:241 242 .. click:run::11 unmodified lines254 @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'))259 260 What it looks like:261 262 .. click:run::7 unmodified lines270 271 @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'))275 276 Callbacks and Eager Options277 ---------------------------278 20 unmodified lines299 300 def print_version(ctx, value):301 if not value:302 return303- print('Version 1.0')303+ click.echo('Version 1.0')304 ctx.exit()305 306 @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!')311 312 The `expose_value` parameter prevents the now pretty pointless ``version``313 parameter to be passed to the callback. If that was not specified a314 boolean would be passed to the `hello` script.23 unmodified lines338 @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!')343 344 And what it looks like on the command line:345 346 .. click:run::8 unmodified lines355 356 @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!')360 361 Values from Environment Variables362 ---------------------------------363 18 unmodified lines382 383 @click.command()384 @click.option('--username')385 def greet(username):386- print('Hello %s!' % username)386+ click.echo('Hello %s!' % username)387 388 if __name__ == '__main__':389 greet(auto_envvar_prefix='GREETER')390 13 unmodified lines404 405 @click.command()406 @click.option('--username', envvar='USERNAME')407 def greet(username):408- print('Hello %s!' % username)408+ click.echo('Hello %s!' % username)409 410 if __name__ == '__main__':411 greet()412 8 unmodified linesmodified:docs/prompts.rst+1 added-1 removed
38 unmodified lines39 function comes in handy. By default it returns the result of the prompt40 as boolean value::41 42 if click.confirm('Do you want to continue?'):43- print('Well done!')43+ click.echo('Well done!')44 45 There is also the option to make it automatically abort the execution::46 47 click.confirm('Do you want to continue?', abort=True)modified:docs/quickstart.rst+23 added-6 removed
22 unmodified lines23 import click24 25 @click.command()26 def hello():27- print('Hello World!')27+ click.echo('Hello World!')28 29 What's happening is that the decorator converts the function into a30 :class:`Command` which then can be invoked::31 11 unmodified lines43 .. click:run::44 45 invoke(hello, args=['--help'])46 47+Echoing48+-------49+50+Why does this example use :func:`echo` instead of the regular51+:func:`print` function? The answer to this question is that click52+attempts to support both Python 2 and Python 3 the same way and to be very53+robust even when the environment is misconfigured. Click wants to be54+functional at least on a basic level even if everything is completely55+broken.56+57+What this means is that the :func:`echo` function applies some error58+correction in case the terminal is misconfigured instead of dying with an59+:exc:`UnicodeError`.60+61+If you don't need this, you can also use the `print()` construct /62+function.63+64 Nesting Commands65 ----------------66 67 Commands can be attached to other commands of type :class:`Group`. This7 unmodified lines75 pass76 77 @click.command()78 def initdb():62- print('Initialized the database')79+ click.echo('Initialized the database')80 81 @click.command()82 def dropdb():66- print('Dropped the database')83+ click.echo('Dropped the database')84 85 cli.add_command(initdb)86 cli.add_command(dropdb)87 13 unmodified lines101 pass102 103 @cli.command()104 def initdb():88- print('Initialized the database')105+ click.echo('Initialized the database')106 107 @cli.command()108 def dropdb():92- print('Dropped the database')109+ click.echo('Dropped the database')110 111 Adding Parameters112 -----------------113 5 unmodified lines119 @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)124 125 What it looks like:126 127 .. click:run::2 unmodified linesmodified:docs/setuptools.rst+1 added-1 removed
32 unmodified lines33 34 @click.command()35 def cli():36 """Example script."""37- print('Hello World!')37+ click.echo('Hello World!')38 39 Contents of ``setup.py``::40 41 from setuptools import setup, find_packages38 unmodified lines