Skip to content
Myr

Capitalized instances of Click (addressing #128)

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

authored by Kevin Yap · committed by Kevin Yap · parent f1a8460 · Browse files · 30 files+118 added−118 removed
This commit

State

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

Diff stats

30 files+118 added−118 removed

  • other:+118 added−118 removed

30 files+118 added−118 removed

modified:click/_termui_impl.py+1 added-1 removed
1 unmodified line
2 click._termui_impl3 ~~~~~~~~~~~~~~~~~~45 This module contains implementations for the termui module. To keep the6 import time of click down, some infrequently used functionality is placed6 import time of Click down, some infrequently used functionality is placed7 in this module and only imported as needed.89 :copyright: (c) 2014 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.
499 unmodified lines
modified:click/core.py+10 added-10 removed
36 unmodified lines
37 code = getattr(callback, '__code__', None)38 args = getattr(code, 'co_argcount', 3)3940 if args < 3:41 # This will become a warning in click 3.0:41 # This will become a warning in Click 3.0:42 from warnings import warn43 warn(Warning('Invoked legacy parameter callback "%s". The new '44 'signature for such callbacks starting with '45 'click 2.0 is (ctx, param, value).'
70 unmodified lines
116 :param terminal_width: the width of the terminal. The default is117 inherit from parent context. If no context118 defines the terminal width then auto119 detection will be applied.120 :param resilient_parsing: if this flag is enabled then click will120 :param resilient_parsing: if this flag is enabled then Click will121 parse without any interactivity or callback122 invocation. This is useful for implementing123 things such as completion support.124 :param help_option_names: optionally a list of strings that define how
57 unmodified lines
182 #: An optional normalization function for tokens. This is183 #: options, choices, commands etc.184 self.token_normalize_func = token_normalize_func185186 #: Indicates if resilient parsing is enabled. In that case click186 #: Indicates if resilient parsing is enabled. In that case Click187 #: will do its best to not cause any failures.188 self.resilient_parsing = resilient_parsing189190 # If there is no envvar prefix yet, but the parent has one and
156 unmodified lines
347class BaseCommand(object):348 """The base command implements the minimal API contract of commands.349 Most code will never use this as it does not implement a lot of useful350 functionality but it can act as the direct subclass of alternative351 parsing methods that do not depend on the click parser.351 parsing methods that do not depend on the Click parser.352353 For instance, this can be used to bridge click and other systems like353 For instance, this can be used to bridge Click and other systems like354 argparse or docopt.355356 Because base commands do not implement a lot of the API that other357 parts of click take for granted, they are not supported for all357 parts of Click take for granted, they are not supported for all358 operations. For instance, they cannot be used with the decorators359 usually and they have no built-in callback system.360361 .. versionchanged:: 2.0
127 unmodified lines
489490491class Command(BaseCommand):492 """Commands are the basic building block of command line interfaces in493 click. A basic command handles command line parsing and might dispatch493 Click. A basic command handles command line parsing and might dispatch494 more parsing to commands nested below it.495496 .. versionchanged:: 2.0497 Added the `context_settings` parameter.
276 unmodified lines
774775776class Group(MultiCommand):777 """A group allows a command to have subcommands attached. This is the778 most common way to implement nesting in click.778 most common way to implement nesting in Click.779780 :param commands: a dictionary of commands.781 """782
80 unmodified lines
863 Some settings are supported by both options and arguments.864865 .. versionchanged:: 2.0866 Changed signature for parameter callback to also be passed the867 parameter. In click 2.0, the old callback format will still work,867 parameter. In Click 2.0, the old callback format will still work,868 but it will raise a warning to give you change to migrate the869 code easier.870871 :param param_decls: the parameter declarations for this option or
7 unmodified lines
879 in which case it's invoked when the default is needed880 without any arguments.881 :param callback: a callback that should be executed after the parameter882 was matched. This is called as ``fn(ctx, param,883 value)`` and needs to return the value. Before click883 value)`` and needs to return the value. Before Click884 2.0, the signature was ``(ctx, value)``.885 :param nargs: the number of arguments to match. If not ``1`` the return886 value is a tuple instead of single value.887 :param metavar: how the value is represented in the help page.
444 unmodified lines
modified:click/decorators.py+1 added-1 removed
214 unmodified lines
215 """Adds a ``--version`` option which immediately ends the program216 printing out the version number. This is implemented as an eager217 option that prints the version and exits the program in the callback.218219 :param version: the version number to show. If not provided click219 :param version: the version number to show. If not provided Click220 attempts an auto discovery via setuptools.221 :param prog_name: the name of the program (defaults to autodetection)222 :param message: custom message to show instead of the default223 (``'%(prog)s, version %(version)s'``)
70 unmodified lines
modified:click/exceptions.py+4 added-4 removed
1 unmodified line
2from .utils import echo345class ClickException(Exception):6 """An exception that click can handle and show to the user."""6 """An exception that Click can handle and show to the user."""78 #: The exit code for this exception9 exit_code = 110
37 unmodified lines
4849class BadParameter(UsageError):50 """An exception that formats out a standardized error message for a51 bad parameter. This is useful when thrown from a callback or type as52 click will attach contextual information to it (for instance, which52 Click will attach contextual information to it (for instance, which53 parameter it is).5455 .. versionadded:: 2.05657 :param param: the parameter object that caused this error. This can58 be left out, and click will attach this info itself58 be left out, and Click will attach this info itself59 if possible.60 :param param_hint: a string that shows up as parameter name. This61 can be used as alternative to `param` in cases62 where custom validation should happen. If it is
34 unmodified lines
97 return 'Could not open file %s: %s' % (self.ui_filename, self.message)9899100class Abort(RuntimeError):101 """An internal signalling exception that signals click to abort."""101 """An internal signalling exception that signals Click to abort."""
modified:click/parser.py+2 added-2 removed
3 unmodified lines
4 ~~~~~~~~~~~~56 This module started out as largely a copy paste from the stdlib's7 optparse module with the features removed that we do not need from8 optparse because we implement them in click on a higher level (for8 optparse because we implement them in Click on a higher level (for9 instance type handling, help formatting and a lot more).1011 The plan is to remove more and more from here over time.12
113 unmodified lines
126class OptionParser(object):127 """The option parser is an internal class that is ultimately used to128 parse options and arguments. It's modelled after optparse and brings129 a similar but vastly simplified API. It should generally not be used130 directly as the high level click classes wrap it for you.130 directly as the high level Click classes wrap it for you.131132 It's not nearly as extensible as optparse or argparse as it does not133 implement features that are implemented on a higher level (such as134 types or defaults).
213 unmodified lines
modified:click/termui.py+1 added-1 removed
354 unmodified lines
355356357def unstyle(text):358 """Removes ANSI styling information from a string. Usually it's not359 necessary to use this function as click's echo function will359 necessary to use this function as Click's echo function will360 automatically remove styling if necessary.361362 .. versionadded:: 2.0363
133 unmodified lines
modified:click/testing.py+3 added-3 removed
90 unmodified lines
91 )929394class CliRunner(object):95 """The CLI runner provides functionality to invoke a click command line95 """The CLI runner provides functionality to invoke a Click command line96 script for unittesting purposes in a isolated environment. This only97 works in single-threaded systems without any concurrency as it changes the98 global interpreter state.99100 :param charset: the character set for the input and output data. This is101 UTF-8 by default and should not be changed currently as102 the reporting to click only works in Python 2 properly.102 the reporting to Click only works in Python 2 properly.103 :param env: a dictionary with environment variables for overriding.104 :param echo_stdin: if this is set to `True`, then reading from stdin writes105 to stdout. This is useful for showing examples in106 some circumstances. Note that regular prompts
25 unmodified lines
132 def isolation(self, input=None, env=None):133 """A context manager that sets up the isolation for invoking of a134 command line tool. This sets up stdin with the given input data135 and `os.environ` with the overrides from the given dictionary.136 This also rebinds some internals in click to be mocked (like the136 This also rebinds some internals in Click to be mocked (like the137 prompt functionality).138139 This is automatically done in the :meth:`invoke` method.140
148 unmodified lines
modified:click/types.py+1 added-1 removed
253 unmodified lines
254 The `lazy` flag controls if the file should be opened immediately or255 upon first IO. The default is to be non lazy for standard input and256 output streams as well as files opened for reading, lazy otherwise.257258 Starting with click 2.0, files can also be opened atomically in which258 Starting with Click 2.0, files can also be opened atomically in which259 case all writes go into a separate file in the same folder and upon260 completion the file will be moved over to the original location. This261 is useful if a file regularly read by other users is modified.262
189 unmodified lines
modified:click/utils.py+2 added-2 removed
157 unmodified lines
158159 def open(self):160 """Opens the file if it's not yet open. This call might fail with161 a :exc:`FileError`. Not handling this error will produce an error162 that click shows.162 that Click shows.163 """164 if self._f is not None:165 return self._f166 try:
47 unmodified lines
214215 .. _colorama: http://pypi.python.org/pypi/colorama216217 .. versionchanged:: 2.0218 Starting with version 2.0 of click, the echo function will work218 Starting with version 2.0 of Click, the echo function will work219 with colorama if it's installed.220221 :param message: the message to print222 :param file: the file to write to (defaults to ``stdout``)
140 unmodified lines
modified:docs/advanced.rst+7 added-7 removed
3 unmodified lines
4.. currentmodule:: click56In addition to common functionality that is implemented in the library7itself, there are countless patterns that can be implemented by extending8click. This page should give some insight into what can be accomplished.8Click. This page should give some insight into what can be accomplished.910.. _aliases:1112Command Aliases
53 unmodified lines
66-------------------6768.. versionadded:: 2.06970Starting with click 2.0, it's possible to provide a function that is used70Starting with Click 2.0, it's possible to provide a function that is used71for normalizing tokens. Tokens are option names, choice values, or command72values. This can be used to implement case insensitive options, for73instance.74
19 unmodified lines
94Invoking Other Commands95-----------------------9697Sometimes, it might be interesting to invoke one command from another98command. This is a pattern that is generally discouraged with click, but98command. This is a pattern that is generally discouraged with Click, but99possible nonetheless. For this, you can use the :func:`Context.invoke`100or :func:`Context.forward` methods.101102They work similarly, but the difference is that :func:`Context.invoke` merely
37 unmodified lines
140programmer with the order of arguments as defined by the user before141invoking any callbacks.142143This is an important concept to understand when porting complex144patterns to click from optparse or other systems. A parameter144patterns to Click from optparse or other systems. A parameter145callback invocation in optparse happens as part of the parsing step,146whereas a callback invocation in click happens after the parsing.146whereas a callback invocation in Click happens after the parsing.147148The main difference is that in optparse, callbacks are invoked with the raw149value as it happens, whereas a callback in click is invoked after the149value as it happens, whereas a callback in Click is invoked after the150value has been fully converted.151152Generally, the order of invocation is driven by the order in which the user153provides the arguments to the script; if there is an option called ``--foo``
19 unmodified lines
173 ``exclude`` and it will be passed both options (``foo`` and174 ``bar``), then the callback for ``include`` will fire with ``baz``175 only.176177 Note that even if a parameter does not allow multiple versions, click177 Note that even if a parameter does not allow multiple versions, Click178 will still accept the position of the first, but it will ignore every179 value except the first. The reason for this is to allow composability180 through shell aliases that set defaults.181
9 unmodified lines
modified:docs/arguments.rst+4 added-4 removed
116 unmodified lines
117-------------------118119In the previous example, the files were opened immediately. But what if120we just want the filename? The naïve way is to use the default string121argument type. However, remember that click is Unicode-based, so the string121argument type. However, remember that Click is Unicode-based, so the string122will always be a Unicode value. Unfortunately, filenames can be Unicode or123bytes depending on which operating system is being used. As such, the type124is insufficient.125
49 unmodified lines
175necessary for manually prompting with the :func:`prompt` function as you176do not know if a stream like stdout was opened (which was already open177before) or a real file that needs closing.178179Starting with click 2.0, it is also possible to open files in atomic mode by179Starting with Click 2.0, it is also possible to open files in atomic mode by180passing ``atomic=True``. In atomic mode, all writes go into a separate181file in the same folder, and upon completion, the file will be moved over to182the original location. This is useful if a file regularly read by other183users is modified.
33 unmodified lines
217---------------------218219Sometimes, you want to process arguments that look like options. For220instance, imagine you have a file named ``-foo.txt``. If you pass this as221an argument in this manner, click will treat it as an option.221an argument in this manner, Click will treat it as an option.222223To solve this, click does what any POSIX style command line script does,223To solve this, Click does what any POSIX style command line script does,224and that is to accept the string ``--`` as a separator for options and225arguments. After the ``--`` marker, all further parameters are accepted as226arguments.227
15 unmodified lines
modified:docs/bashcomplete.rst+4 added-4 removed
1 unmodified line
2=============34.. versionadded:: 2.056As of click 2.0, there is built-in support for Bash completion for7any click script. There are certain restrictions on when this completion6As of Click 2.0, there is built-in support for Bash completion for7any Click script. There are certain restrictions on when this completion8is available, but for the most part it should just work.910Limitations11-----------1213Bash completion is only available if a script has been installed properly,14and not executed through the ``python`` command. For information about15how to do that, see :ref:`setuptools-integration`. Also, click currently15how to do that, see :ref:`setuptools-integration`. Also, Click currently16only supports completion for Bash.1718Currently, Bash completion is an internal feature that is not customizable.19This might be relaxed in future versions.
13 unmodified lines
33Activation34----------3536In order to activate Bash completion, you need to inform Bash that37completion is available for your script, and how. Any click application37completion is available for your script, and how. Any Click application38automatically provides support for that. The general way this works is39through a magic environment variable called ``_<PROG_NAME>_COMPLETE``,40where ``<PROG_NAME>`` is your application executable name in uppercase41with dashes replaced by underscores.
28 unmodified lines
modified:docs/commands.rst+2 added-2 removed
1 unmodified line
2===================34.. currentmodule:: click56The most important feature of click is the concept of arbitrarily nesting6The most important feature of Click is the concept of arbitrarily nesting7command line utilities. This is implemented through the :class:`Command`8and :class:`Group` (actually :class:`MultiCommand`).910Callback Invocation
296 unmodified lines
307----------------308309.. versionadded:: 2.0310311Starting with click 2.0 you can override defaults for contexts not just311Starting with Click 2.0 you can override defaults for contexts not just312when calling your script, but also in the decorator that declares a313command. For instance given the previous example which defines a custom314``default_map`` this can also be accomplished in the decorator now.315
27 unmodified lines
modified:docs/complex.rst+4 added-4 removed
10 unmodified lines
11have realized that it provides a command line utility, but so does Celery.12When using Celery with Django, there are two tools that need to interact with13each other and be cross-configured.1415In a theoretical world of two separate click command line utilities, they15In a theoretical world of two separate Click command line utilities, they16could solve this problem by nesting one inside the other. For instance, the17web framework could also load the commands for the message queue framework.1819Basic Concepts
4 unmodified lines
2425Contexts26````````2728Whenever a click command is executed, a :class:`Context` object is created28Whenever a Click command is executed, a :class:`Context` object is created29which holds state for this particular invocation. It remembers parsed30parameters, what command created it, which resources need to be cleaned up31at the end of the function, and so forth. It can also optionally hold an32application-defined object.
11 unmodified lines
4445Calling Convention46``````````````````4748When a click command callback is executed, it's passed all the non-hidden48When a Click command callback is executed, it's passed all the non-hidden49parameters as keyword arguments. Notably absent is the context. However,50a callback can opt into being passed to the context object by marking itself51with :func:`pass_context`.52
15 unmodified lines
68````````````````6970At the top level, we need a group that can hold all our commands. In this71case, we use the basic :func:`click.group` which allows us to register72other click commands below it.72other Click commands below it.7374For this command, we also want to accept some parameters that configure the75state of our tool:76
143 unmodified lines
modified:docs/documentation.rst+3 added-3 removed
38 unmodified lines
3940Preventing Rewrapping41---------------------4243The default behavior of click is to rewrap text based on the width of the43The default behavior of Click is to rewrap text based on the width of the44terminal. In some circumstances, this can become a problem. The main issue45is when showing code examples, where newlines are significant.4647Rewrapping can be disabled on a per-paragraph basis by adding a line with
87 unmodified lines
135----------------------------136137.. versionadded:: 2.0138139The help parameter is implemented in click in a very special manner.140Unlike regular parameters it's automatically added by click for any139The help parameter is implemented in Click in a very special manner.140Unlike regular parameters it's automatically added by Click for any141command and it performs automatic conflict resolution. By default it's142called ``--help``, but this can be changed. If a command itself implements143a parameter with the same name, the default help parameter stops accepting144it. There is a context setting that can be used to override the names of
18 unmodified lines
modified:docs/index.rst+1 added-1 removed
14 unmodified lines
15- arbitrary nesting of commands16- automatic help page generation17- supports lazy loading of subcommands at runtime1819What does it look like? Here is an example of a simple click program:19What does it look like? Here is an example of a simple Click program:2021.. click:example::2223 import click
74 unmodified lines
modified:docs/license.rst+1 added-1 removed
1License2=======34Click is licensed under a three-clause BSD License. It basically means:5do whatever you want with it as long as the copyright in click sticks5do whatever you want with it as long as the copyright in Click sticks6around, the conditions are not modified and the disclaimer is present.7Furthermore, you must not use the names of the authors to promote derivatives8of the software without written consent.9
4 unmodified lines
modified:docs/options.rst+14 added-14 removed
100 unmodified lines
101102Boolean flags are options that can be enabled or disabled. This can be103accomplished by defining two flags in one go separated by a slash (``/``)104for enabling or disabling the option. (If a slash is in an option string,105click automatically knows that it's a boolean flag and will pass105Click automatically knows that it's a boolean flag and will pass106``is_flag=True`` implicitly.) Click always wants you to provide an enable107and disable flag so that you can change the default later.108109Example:
17 unmodified lines
127 invoke(info, args=['--shout'])128 invoke(info, args=['--no-shout'])129130If you really don't want an off-switch, you can just define one and131manually inform click that something is a flag:131manually inform Click that something is a flag:132133.. click:example::134135 import os
31 unmodified lines
167168In addition to boolean flags, there are also feature switches. These are169implemented by setting multiple options to the same parameter name and170defining a flag value. Note that by providing the ``flag_value`` parameter,171click will implicitly set ``is_flag=True``.171Click will implicitly set ``is_flag=True``.172173To set a default flag, assign a value of `True` to the flag that should be174the default.175
50 unmodified lines
226---------227228In some cases, you want parameters that can be provided from the command line,229but if not provided, ask for user input instead. This can be implemented with230click by defining a prompt string.230Click by defining a prompt string.231232Example:233234.. click:example::
95 unmodified lines
330331The `expose_value` parameter prevents the pretty pointless ``version``332parameter from being passed to the callback. If that was not specified, a333boolean would be passed to the `hello` script. The `resilient_parsing`334flag is applied to the context if click wants to parse the command line334flag is applied to the context if Click wants to parse the command line335without any destructive behavior that would change the execution flow. In336this case, because we would exit the program, we instead do nothing.337338What it looks like:
4 unmodified lines
343 invoke(hello, args=['--version'])344345.. admonition:: Callback Signature Changes346347 In click 2.0 the signature for callbacks changed. For more347 In Click 2.0 the signature for callbacks changed. For more348 information about these changes see :ref:`upgrade-to-2.0`.349350Yes Parameters351--------------
34 unmodified lines
386 click.echo('Dropped all tables!')387388.. admonition:: Callback Signature Changes389390 In click 2.0 the signature for callbacks changed. For more390 In Click 2.0 the signature for callbacks changed. For more391 information about these changes see :ref:`upgrade-to-2.0`.392393Values from Environment Variables394---------------------------------395396A very useful feature of click is the ability to accept parameters from396A very useful feature of Click is the ability to accept parameters from397environment variables in addition to regular parameters. This allows398tools to be automated much easier. For instance, you might want to pass399a configuration file with a ``--config`` parameter but also support exporting400a ``TOOL_CONFIG=hello.cfg`` key-value pair for a nicer development401experience.402403This is supported by click in two ways. One is to automatically build403This is supported by Click in two ways. One is to automatically build404environment variables which is supported for options only. To enable this405feature, the ``auto_envvar_prefix`` parameter needs to be passed to the406script that is invoked. Each command and parameter is then added as an407uppercase underscore-separated variable. If you have a subcommand
47 unmodified lines
455---------------------------------------456457As options can accept multiple values, pulling in such values from458environment variables (which are strings) is a bit more complex. The way459click solves this is by leaving it up to the type to customize this459Click solves this is by leaving it up to the type to customize this460behavior. For both ``multiple`` and ``nargs`` with values other than461``1``, click will invoke the :meth:`ParamType.split_envvar_value` method to461``1``, Click will invoke the :meth:`ParamType.split_envvar_value` method to462perform the splitting.463464The default implementation for all types is to split on whitespace. The465exceptions to this rule are the :class:`File` and :class:`Path` types
27 unmodified lines
493494Click can deal with alternative prefix characters other than ``-`` for495options. This is for instance useful if you want to handle slashes as496parameters ``/`` or something similar. Note that this is strongly497discouraged in general because click wants developers to stay close to497discouraged in general because Click wants developers to stay close to498POSIX semantics. However in certain situations this can be useful:499500.. click:example::501
72 unmodified lines
574If you want to apply custom validation logic, you can do this in the575parameter callbacks. These callbacks can both modify values as well as576raise errors if the validation does not work.577578In click 1.0, you can only raise the :exc:`UsageError` but starting with579click 2.0, you can also raise the :exc:`BadParameter` error, which has the578In Click 1.0, you can only raise the :exc:`UsageError` but starting with579Click 2.0, you can also raise the :exc:`BadParameter` error, which has the580added advantage that it will automatically format the error message to581also contain the parameter name.582583Example:
25 unmodified lines
modified:docs/python3.rst+12 added-12 removed
6 unmodified lines
7it suffers from the Unicode text model in Python 3. All examples in the8documentation were written so that they could run on both Python 2.x and9Python 3.3 or higher.1011At the moment, it is strongly recommended is to use Python 2 for click11At the moment, it is strongly recommended is to use Python 2 for Click12utilities unless Python 3 is a hard requirement.1314.. _python3-limitations:1516Python 3 Limitations17--------------------1819At the moment, click suffers from a few problems with Python 3:19At the moment, Click suffers from a few problems with Python 3:2021* The command line in Unix traditionally is in bytes, and not Unicode.22 While there are encoding hints for all of this, there are generally23 some situations where this can break. The most common one is SSH24 connections to machines with different locales.2526 Misconfigured environments can currently cause a wide range of Unicode27 problems in Python 3 due to the lack of support for roundtripping28 surrogate escapes. This will not be fixed in click itself!28 surrogate escapes. This will not be fixed in Click itself!2930 For more information see :ref:`python3-surrogates`.3132* Standard input and output in Python 3 is opened in Unicode mode by
34 unmodified lines
67* ``sys.argv`` is always byte-based. Click will pass bytes to all68 input types and convert as necessary. The :class:`STRING` type69 automatically will decode properly the input value into a string by70 trying the most appropriate encodings.71* When dealing with files, click will never go through the Unicode APIs71* When dealing with files, Click will never go through the Unicode APIs72 and will instead use the operating system's byte APIs to open the73 files.7475In Python 3, the following is true:7677* ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are by default78 text-based. When click needs a binary stream, it attempts to discover78 text-based. When Click needs a binary stream, it attempts to discover79 the underlying binary stream. See :ref:`python3-limitations` for how80 this works.81* ``sys.argv`` is always Unicode-based. This also means that the native82 type for input values to the types in click is Unicode, and not bytes.82 type for input values to the types in Click is Unicode, and not bytes.8384 This causes problems when the terminal is incorrectly set and Python85 does not figure out the encoding. In that case, the Unicode string86 will contain error bytes encoded as surrogate escapes.87* When dealing with files, click will always use the Unicode file system87* When dealing with files, Click will always use the Unicode file system88 API calls by using the operating system's reported or guessed89 filesystem encoding. Surrogates are supported for filenames, so it90 should be possible to open files through the :class:`File` type even91 if the environment is misconfigured.
3 unmodified lines
95Python 3 Surrogate Handling96---------------------------9798Click in Python 3 does all the Unicode handling in the standard library99and is subject to its behavior. In Python 2, click does all the Unicode99and is subject to its behavior. In Python 2, Click does all the Unicode100handling itself, which means there are differences in error behavior.101102The most glaring difference is that in Python 2, Unicode will "just work",103while in Python 3, it requires extra care. The reason for this is that on104Python 3, the encoding detection is done in the interpreter and on Linux105and certain other operating systems its encoding handling is problematic.106107The biggest source of frustration is that click scripts invoked by107The biggest source of frustration is that Click scripts invoked by108init systems (sysvinit, upstart, systemd, etc.), deployment tools (salt,109puppet), or cron jobs (cron) will refuse to work unless a Unicode locale is110exported.111112If click encounters such an environment it will prevent further execution113to force you to set a locale. This is done because click cannot know112If Click encounters such an environment it will prevent further execution113to force you to set a locale. This is done because Click cannot know114about the state of the system once it's invoked and restore the values115before Python's Unicode handling kicked in.116117If you see something like this error in Python 3::
31 unmodified lines
149 <http://bugs.python.org/issue19977>`_150* `Python 3 raises Unicode errors in the C locale151 <http://bugs.python.org/issue19846>`_152* `LC_CTYPE=C: pydoc leaves terminal in an unusable state153 <http://bugs.python.org/issue21398>`_ (this is relevant to click153 <http://bugs.python.org/issue21398>`_ (this is relevant to Click154 because the pager support is provided by the stdlib pydoc module)
modified:docs/quickstart.rst+5 added-5 removed
8 unmodified lines
910Screencast and Examples11-----------------------1213There is a screencast available which shows the basic API of click and13There is a screencast available which shows the basic API of Click and14how to build simple applications with it. It also explores how to build15commands with subcommands.1617* `Building Command Line Applications with Click18 <https://www.youtube.com/watch?v=kNke39OZ2k0>`_1920Examples of click applications can be found in the documentation as well20Examples of Click applications can be found in the documentation as well21as in the GitHub repository together with readme files:2223* ``inout``: `File input and output24 <https://github.com/mitsuhiko/click/tree/master/examples/inout>`_
18 unmodified lines
43Click is based on declaring commands through decorators. Internally, there44is a non-decorator interface for advanced use cases, but it's discouraged45for high-level usage.4647A function becomes a click command line tool by decorating it through47A function becomes a Click command line tool by decorating it through48:func:`click.command`. At its simplest, just decorating a function49with this decorator will make it into a callable script:5051.. click:example::
25 unmodified lines
77Echoing78-------7980Why does this example use :func:`echo` instead of the regular81:func:`print` function? The answer to this question is that click81:func:`print` function? The answer to this question is that Click82attempts to support both Python 2 and Python 3 the same way and to be very83robust even when the environment is misconfigured. Click wants to be84functional at least on a basic level even if everything is completely85broken.
1 unmodified line
87What this means is that the :func:`echo` function applies some error88correction in case the terminal is misconfigured instead of dying with an89:exc:`UnicodeError`.9091As an added benefit, starting with click 2.0, the echo function also91As an added benefit, starting with Click 2.0, the echo function also92has good support for ANSI colors. It will automatically strip ANSI codes93if the output stream is a file and if colorama is supported, ANSI colors94will also work on Windows. See :ref:`ansi-colors` for more information.95
68 unmodified lines
modified:docs/setuptools.rst+1 added-1 removed
57 unmodified lines
5859The magic is in the ``entry_points`` parameter. Below ``console_scripts``,60each line identifies one console script. The first part before the equals61sign (``=``) is the name of the script that should be generated, the second62part is the import path followed by a colon (``:``) with the click62part is the import path followed by a colon (``:``) with the Click63command.6465That's it.66
15 unmodified lines
modified:docs/testing.rst+2 added-2 removed
1 unmodified line
2==========================34.. currentmodule:: click.testing56For basic testing, click provides the :mod:`click.testing` module which6For basic testing, Click provides the :mod:`click.testing` module which7provides test functionality that helps you invoke command line8applications and check their behavior.910These tools should really only be used for testing as they change
2 unmodified lines
1314Basic Testing15-------------1617The basic functionality for testing click applications is the17The basic functionality for testing Click applications is the18:class:`CliRunner` which can invoke commands as command line scripts. The19:meth:`CliRunner.invoke` method runs the command line script in isolation20and captures the output as both bytes and binary data.21
69 unmodified lines
modified:docs/upgrading.rst+4 added-4 removed
14 unmodified lines
15callbacks. Before 2.0, the callback was invoked with ``(ctx, value)``16whereas now it's ``(ctx, param, value)``. This change was necessary as it17otherwise made reusing callbacks too complicated.1819To ease the transition click will still accept old callbacks. Starting20with click 3.0 it will start to issue a warning to stderr to encourage you19To ease the transition Click will still accept old callbacks. Starting20with Click 3.0 it will start to issue a warning to stderr to encourage you21to upgrade.2223In case you want to support both click 1.0 and click 2.0, you can make a23In case you want to support both Click 1.0 and Click 2.0, you can make a24simple decorator that adjusts the signatures::2526 import click27 from functools import update_wrapper
10 unmodified lines
38 @compatcallback39 def callback(ctx, param, value):40 return value.upper()4142Note that because click 1.0 did not pass a parameter, the `param` argument42Note that because Click 1.0 did not pass a parameter, the `param` argument43here would be `None`, so a compatibility callback could not use that44argument.
modified:docs/utils.rst+6 added-6 removed
1 unmodified line
2=========34.. currentmodule:: click56Besides the functionality that click provides to interface with argument6Besides the functionality that Click provides to interface with argument7parsing and handling, it also provides a bunch of addon functionality that8is useful for writing command line utilities.910
26 unmodified lines
37-----------3839.. versionadded:: 2.04041Starting with click 2.0, the :func:`echo` function gained extra41Starting with Click 2.0, the :func:`echo` function gained extra42functionality to deal with ANSI colors and styles. Note that on Windows,43this functionality is only available if `colorama`_ is installed. If it44is installed, then ANSI codes are intelligently handled.4546Primarily this means that:4748- click's :func:`echo` function will automatically strip ANSI color codes48- Click's :func:`echo` function will automatically strip ANSI color codes49 if the stream is not connected to a terminal.50- the :func:`echo` function will transparently connect to the terminal on51 Windows and translate ANSI codes to terminal API calls. This means52 that colors will work on Windows the same way they do on other53 operating systems.5455Note for `colorama` support: click will automatically detect when `colorama`55Note for `colorama` support: Click will automatically detect when `colorama`56is available and use it. Do *not* call ``colorama.init()``!5758To install `colorama`, run this command::59
40 unmodified lines
100101.. versionadded:: 2.0102103To clear the terminal screen, you can use the :func:`clear` function that104is provided starting with click 2.0. It does what the name suggests: it104is provided starting with Click 2.0. It does what the name suggests: it105clears the entire visible screen in a platform-agnostic way:106107::108
10 unmodified lines
119standard input. However, this is buffered input and will not show up until120the line has been terminated. In certain circumstances, you might not want121to do that and instead read individual characters as they are being written.122123For this, click provides the :func:`getchar` function which reads a single123For this, Click provides the :func:`getchar` function which reads a single124character from the terminal buffer and returns it as a Unicode character.125126Note that this function will always read from the terminal, even if stdin127is instead a pipe.
209 unmodified lines
modified:docs/why.rst+18 added-18 removed
1Why Click?2==========34There are so many libraries out there for writing command line utilities;5why does click exist?5why does Click exist?67This question is easy to answer: because there is not a single command8line utility for Python out there which ticks the following boxes:9
7 unmodified lines
17* comes with useful common helpers (getting terminal dimensions,18 ANSI colors, fetching direct keyboard input, screen clearing,19 finding config paths, launching apps and editors, etc.)2021There are many alternatives to click and you can have a look at them if21There are many alternatives to Click and you can have a look at them if22you enjoy them better. The obvious ones are ``optparse`` and ``argparse``23from the standard library.2425Click is actually implemented as a wrapper around a mild fork of
4 unmodified lines
3031Click is designed to be fun to work with and at the same time not stand in32your way. It's not overly flexible either. Currently, for instance, it33does not allow you to customize the help pages too much. This is intentional34because click is designed to allow you to nest command line utilities. The34because Click is designed to allow you to nest command line utilities. The35idea is that you can have a system that works together with another system by36tacking two click instances together and they will continue working as they36tacking two Click instances together and they will continue working as they37should.3839Too much customizability would break this promise.4041Click was written to support the `Flask <http://flask.pocoo.org/>`_42microframework ecosystem because no tool could provide it with the43functionality it needed.4445To get an understanding of what click is all about, I strongly recommend45To get an understanding of what Click is all about, I strongly recommend46looking at the :ref:`complex-guide` chapter to see what it's useful for.4748Why not Argparse?49-----------------5051Click is internally based on optparse instead of argparse. This however52is an implementation detail that a user does not have to be concerned53with. The reason however click is not using argparse is that it has some53with. The reason however Click is not using argparse is that it has some54problematic behaviors that make handling arbitrary command line interfaces55hard:5657* argparse has built-in magic behavior to guess if something is an58 argument or an option. This becomes a problem when dealing with59 incomplete command lines as it's not possible to know without having a60 full understanding of the command line how the parser is going to61 behave. This goes against click's ambitions of dispatching to61 behave. This goes against Click's ambitions of dispatching to62 subparsers.63* argparse currently does not support disabling of interspearsed64 arguments. Without this feature it's not possible to safely implement65 click's nested parsing nature.65 Click's nested parsing nature.6667Why not Docopt etc.?68--------------------6970Docopt and many tools like it are cool in how they work, but very few of71these tools deal with nesting of commands and composability in a way like72click. To the best of the developer's knowledge, click is the first72Click. To the best of the developer's knowledge, Click is the first73Python library that aims to create a level of composability of applications74that goes beyond what the system itself supports.7576Docopt, for instance, acts by parsing your help pages and then parsing
10 unmodified lines
87support dispatching to subcommands, it for instance does not directly88support any kind of automatic subcommand enumeration based on what's89available or it does not enforce subcommands to work in a consistent way.9091This is fine, but it's different from how click wants to work. Click aims91This is fine, but it's different from how Click wants to work. Click aims92to support fully composable command line user interfaces by doing the93following:9495- Click does not just parse, it also dispatches to the appropriate code.
7 unmodified lines
103 written by a different developer will not suddenly die with a104 different error messsage because it's manually handled.105- Click has enough meta information available for its whole program106 that it can evolve over time to improve the user experience without107 forcing developers to adjust their programs. For instance, if click108 decides to change how help pages are formatted, all click programs107 forcing developers to adjust their programs. For instance, if Click108 decides to change how help pages are formatted, all Click programs109 will automatically benefit from this.110111The aim of click is to make composable systems, whereas the aim of docopt111The aim of Click is to make composable systems, whereas the aim of docopt112is to build the most beautiful and hand-crafted command line interfaces.113These two goals conflict with one another in subtle ways. Click114actively prevents people from implementing certain patterns in order to115achieve unified command line interfaces. You have very little input on
2 unmodified lines
118119Why Hardcoded Behaviors?120------------------------121122The other question is why click goes away from optparse and hardcodes122The other question is why Click goes away from optparse and hardcodes123certain behaviors instead of staying configurable. There are multiple124reasons for this. The biggest one is that too much configurability makes125it hard to achieve a consistent command line experience.126
1 unmodified line
128accepting arbitrary number of arguments. Due to syntactical ambiguities129on the command line, there is no way to implement fully variadic arguments.130There are always tradeoffs that need to be made and in case of131``argparse`` these tradeoffs have been critical enough, that a system like132click cannot even be implemented on top of it.132Click cannot even be implemented on top of it.133134In this particular case, click attempts to stay with a handful of accepted134In this particular case, Click attempts to stay with a handful of accepted135paradigms for building command line interfaces that can be well documented136and tested.137138139Why No Auto Correction?140-----------------------141142The question came up why click does not auto correct parameters given that142The question came up why Click does not auto correct parameters given that143even optparse and argparse support automatic expansion of long arguments.144The reason for this is that it's a liability for backwards compatibility.145If people start relying on automatically modified parameters and someone146adds a new parameter in the future, the script might stop working. These147kinds of problems are hard to find so click does not attempt to be magical147kinds of problems are hard to find so Click does not attempt to be magical148about this.149150This sort of behavior however can be implemented on a higher level to151support things such as explicit aliases. For more information see
1 unmodified line
modified:examples/aliases/README+1 added-1 removed
1$ aliases_23 aliases is a fairly advanced example that shows how4 to implement command aliases with click. It uses a4 to implement command aliases with Click. It uses a5 subclass of the default group to customize how commands6 are located.78 It supports both aliases read from a config file as well
9 unmodified lines
modified:examples/complex/README+1 added-1 removed
6 unmodified lines
7 All the commands are implemented as plugins in the8 `complex.commands` package. If a python module is9 placed named "cmd_foo" it will show up as "foo"10 command and the `cli` object within it will be11 loaded as nested click command.11 loaded as nested Click command.1213Usage:1415 $ pip install --editable .
1 unmodified line
modified:examples/termui/README+1 added-1 removed
1$ termui_23 termui showcases the different terminal UI helpers that4 click provides.4 Click provides.56Usage:78 $ pip install --editable .
1 unmodified line
modified:examples/README+1 added-1 removed
1Click Examples23 This folder contains various click examples. Note that3 This folder contains various Click examples. Note that4 all of these are not runnable by themselves but should be5 installed into a virtualenv.67 This is done this way so that scripts also properly work
5 unmodified lines
modified:CHANGES+1 added-1 removed
1Click Changelog2===============34This contains all major version changes between click releases.4This contains all major version changes between Click releases.56Version 3.07-----------8
82 unmodified lines