Skip to content
Myr

Documentation fixes

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

authored by Kevin Yap · committed by Armin Ronacher · parent f48761a · Browse files · 17 files+193 added−193 removed
This commit

State

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

Diff stats

17 files+193 added−193 removed

  • other:+193 added−193 removed

17 files+193 added−193 removed

modified:docs/advanced.rst+15 added-15 removed
21 unmodified lines
22functionality.2324As explained in :ref:`custom-multi-commands`, a multi command can provide25two methods: :meth:`~MultiCommand.list_commands` and26:meth:`~MultiCommand.get_command`. In this particular case you only need26:meth:`~MultiCommand.get_command`. In this particular case, you only need27to override the latter as you generally don't want to enumerate the28aliases on the help page to avoid confusion.28aliases on the help page in order to avoid confusion.2930This following example implements a subclass of :class:`Group` that31accepts a prefix for a command. If there is a command called32``push`` it would accept ``pus`` as an alias if it's unique:31accepts a prefix for a command. If there were a command called32``push``, it would accept ``pus`` as an alias if it was unique:3334.. click:example::3536 class AliasedGroup(click.Group):
29 unmodified lines
66Invoking Other Commands67-----------------------6869Sometimes, it might be interesting to invoke one command from another70command. This is a pattern that is generally discouraged with click but71possible nonetheless. For this you can use the :func:`Context.invoke`70command. This is a pattern that is generally discouraged with click, but71possible nonetheless. For this, you can use the :func:`Context.invoke`72or :func:`Context.forward` methods.7374They work similarly, but the difference is that :func:`Context.invoke` merely75invokes another command with the arguments you provide as a caller,
30 unmodified lines
106107Callback Evaluation Order108-------------------------109110Click works a bit different than some other command line parsers in that110Click works a bit differently than some other command line parsers in that111it attempts to reconcile the order of arguments as defined by the112programmer with the order of arguments as defined by the user before113invoking any callbacks.114115This is an important concept to understand when implementing complex116patterns ported from optparse or other systems to click. A parameter117callback invocation in optparse happens as part of the parsing step115This is an important concept to understand when porting complex116patterns to click from optparse or other systems. A parameter117callback invocation in optparse happens as part of the parsing step,118whereas a callback invocation in click happens after the parsing.119120The main difference is that in optparse callbacks are invoked with the raw120The main difference is that in optparse, callbacks are invoked with the raw121value as it happens, whereas a callback in click is invoked after the122value has been fully converted.123124Generally, the order of invocation is driven by the order in which the user
13 unmodified lines
138 comes first on the command line will win and exit the program.139140Repeated parameters:141 If an option or argument is split up on the command line into multiple142 places because it's repeated (for instance ``--exclude foo --include143 baz --exclude bar``), the callback will fire based on the position of142 places because it is repeated -- for instance, ``--exclude foo --include143 baz --exclude bar`` -- the callback will fire based on the position of144 the first option. In this case, the callback will fire for145 ``exclude`` and it will be passed both options (``foo`` and146 ``bar``), then the callback for ``include`` will fire with ``baz``147 only.
9 unmodified lines
157 undefined values do not fire the callback. Missing parameters fire158 their callbacks at the very end which makes it possible for them to159 default to values from a parameter that came before.160161Most of the time you don't need to be concerned about any of this stuff,162but it's important to know how it works for some advanced cases.161Most of the time you do not need to be concerned about any of this,162but it is important to know how it works for some advanced cases.
modified:docs/arguments.rst+29 added-29 removed
1 unmodified line
2=========34.. currentmodule:: click56Arguments work similar to options but are positional. They also only6Arguments work similarly to options, but are positional. They also only7support a subset of the features of options due to their syntactical nature.8Click also will not attempt to document arguments for you and wants you to9document them manually to avoid ugly looking help pages.8Click will also not attempt to document arguments for you and wants you to9document them manually in order to avoid ugly help pages.1011Basic Arguments12---------------1314The most basic option is a simple string argument of one value. If no15type is provided the type of the default value is used. If no default16value is provided the type is assumed to be :data:`STRING`.15type is provided, the type of the default value is used, and if no default16value is provided, the type is assumed to be :data:`STRING`.1718Example:1920.. click:example::
13 unmodified lines
34------------------3536The second most common version is variadic arguments where a specific (or37unlimited) number of arguments is accepted. This can be controlled with38the ``nargs`` parameter. If it's set to ``-1`` then an unlimited number38the ``nargs`` parameter. If it is set to ``-1``, then an unlimited number39of arguments is accepted.4041The value is then passed as a tuple. Note that only one argument can be42set to ``nargs=-1`` as this will eat up all arguments.42set to ``nargs=-1``, as it will eat up all arguments.4344Example:4546.. click:example::
12 unmodified lines
59 invoke(copy, args=['foo.txt', 'bar.txt', 'my_folder'])6061Note that this is not how you would write this application. The reason62for this is that in this particular example the arguments are defined as63strings. File names however are not strings! They might be (on certain64operating systems) but not necessarily on others. For better ways see the65next sections.63strings. Filenames, however, are not strings! They might be on certain64operating systems, but not necessarily on all. For better ways to write65this, see the next sections.6667.. admonition:: Note on Non-Empty Variadic Arguments6869 If you come from ``argparse`` you might be missing support for setting
12 unmodified lines
82--------------8384Since all the examples have already worked with filenames, it makes sense85to explain how to deal with files properly. Command line tools are more86fun if they work with files the Unix way which is to accept ``-`` as a86fun if they work with files the Unix way, which is to accept ``-`` as a87special file that refers to stdin/stdout.8889Click supports this through the :class:`click.File` type which90intelligently handles files for you. It also deals with Unicode and bytes
26 unmodified lines
117-------------------118119In the previous example the files were opened immediately. But what if120we just want the filename? The naive way is to use the default string121argument type. However remember that click is unicode based so the string122will be a unicode value always. Filenames unfortunately however can be123unicode or bytes depending on which operating system you're on. As such124the type is insufficient.121argument 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.125126Instead, you should be using the :class:`Path` type which handles this126Instead, you should be using the :class:`Path` type, which handles this127complexity for you. Not only will it return either bytes or Unicode128depending on what makes more sense, but it will also be able to do some129basic checks for you such as existence checks.130
20 unmodified lines
151152File Opening Safety153-------------------154155The :class:`FileType` type has one problem it needs to deal with and that155The :class:`FileType` type has one problem it needs to deal with, and that156is to decide when to open a file. The default behavior is to be157"intelligent" about it. What this means is that it will open stdin/stdout158and files opened for reading immediately. This will directly give the159user feedback when a file cannot be opened, but it will only open files160for writing the first time an IO operation is performed by wrapping the161file automatically in a special wrapper.158and files opened for reading immediately. This will give the user direct159feedback when a file cannot be opened, but it will only open files160for writing the first time an IO operation is performed by automatically161wrapping the file in a special wrapper.162163This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` to164the constructor. If the file is opened lazily, it will fail on first IO164the constructor. If the file is opened lazily, it will fail its first IO165operation by raising an :exc:`FileError`.166167Since files opened for writing will typically immediately empty the file,168the lazy mode should only be disabled if the developer is absolutely sure
6 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's 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 to181file 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.184185Environment Variables186---------------------187188Like options, arguments can also get values from an environment variable.188Like options, arguments can also grab values from an environment variable.189Unlike options, however, this is only supported for explicitly named190environment variables.191192Example usage:
16 unmodified lines
209210In that case, it can also be a list of different environment variables211where the first one is picked.212213Generally this feature is not recommended because it can cause a lot of214confusion to the user.213Generally, this feature is not recommended because it can cause the user214a lot of confusion.215216Arguments-Like Options216Argument-Like Options217------------------------------218219Sometimes you want to process arguments that look like options. For219Sometimes, 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.222223To solve this, click does what any POSIX style command line script does,
19 unmodified lines
modified:docs/bashcomplete.rst+10 added-10 removed
8 unmodified lines
910Limitations11-----------1213Bash completion is only available if a script has been installed properly13Bash 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 currently16only supports completion for bash.15how 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.18Currently, Bash completion is an internal feature that is not customizable.19This might be relaxed in future versions.2021What it Completes22-----------------2324Generally, the bash completion support will complete subcommands and24Generally, the Bash completion support will complete subcommands and25parameters. Subcommands are always listed whereas parameters only if at26least a dash has been provided. Example::2728 $ repo <TAB><TAB>
3 unmodified lines
3233Activation34----------3536In order to activate Bash completion you need to inform Bash that37completion is available for your script and how. Any click application36In order to activate Bash completion, you need to inform Bash that37completion 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.
6 unmodified lines
48is what you would need to put into your ``.bashrc``::4950 eval "$(_FOO_BAR_COMPLETE=source foo-bar)"5152From this point onwards your script will have Bash completion enabled.52From this point onwards, your script will have Bash completion enabled.5354Activation Script55-----------------5657The above activation example will always invoke your application on58startup. This might be slowing down the shell activation time59significantly if you have many applications. Alternatively you could also60ship a file with the contents of that which is what Git and other systems59significantly if you have many applications. Alternatively, you could also60ship a file with the contents of that, which is what Git and other systems61are doing.6263This can be easily accomplished::64
5 unmodified lines
modified:docs/commands.rst+7 added-7 removed
9 unmodified lines
10Callback Invocation11-------------------1213For a regular command, the callback is executed whenever the command runs.14If the script is the only command it will always fire (unless a14If the script is the only command, it will always fire (unless a15parameter callback prevents it). This for instance happens if someone16passes ``--help`` to the script).1718For groups and multi commands, the situation looks different. In this case,
94 unmodified lines
113 return update_wrapper(new_func, f)114115The :meth:`Context.invoke` command will automatically invoke the function116in the correct way, so the function will either be called with ``f(ctx,117obj)`` or ``f(obj)`` depending on if it itself is decorated with117obj)`` or ``f(obj)`` depending on whether or not it itself is decorated with118:func:`with_context`.119120This is a very powerful context that can be used to build very complex121nested applications. See :ref:`complex-guide` for more information.121nested applications; see :ref:`complex-guide` for more information.122123124Group Invocation Without Command125--------------------------------
84 unmodified lines
210----------------------211212In addition to implementing custom multi commands, it can also be213interesting to merge multiple together into one script. While this is214generally not as recommended as nesting one below the other, the merging214generally not as recommended as it nests one below the other, the merging215approach can be useful in some circumstances for a nicer shell experience.216217A default implementation for such a merging system is the217The default implementation for such a merging system is the218:class:`CommandCollection` class. It accepts a list of other multi219commands and makes the commands available on the same level.220221Example usage:
43 unmodified lines
265266This is useful if you plug in some commands from another package but267you're not satisfied with the defaults.268269The default map can be nested arbitrarily for each subcommand and be269The default map can be nested arbitrarily for each subcommand and270provided when the script is invoked. Alternatively, it can also be271overriden at any point by commands. For instance a top-level command could271overriden at any point by commands. For instance, a top-level command could272load the defaults from a configuration file.273274Example usage:275
27 unmodified lines
modified:docs/complex.rst+17 added-18 removed
5 unmodified lines
6.. currentmodule:: click78Click is designed to assist with the creation of complex and simple CLI tools9alike. However, the power of its design is the ability to arbitrarily nest10systems together. For instance, in case you have ever used Django, you will11have realized that it provides a command line utility, but so does Celery (for12instance). When using Celery with Django there are two tools that need13to interact with each other and be cross configured.10systems together. For instance, if you have ever used Django, you will11have 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 they16can solve this problem by nesting one inside the other. For instance, the17web framework could also load the commands for the message queue18framework.15In 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 Concepts20--------------2123To understand how this works you need to understand two concepts: contexts22To understand how this works, you need to understand two concepts: contexts23and the calling convention.2425Contexts26````````
3 unmodified lines
30parameters, 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.3335Context objects build a linked list until they hit top one. Each context34Context objects build a linked list until they hit the top one. Each context35is linked to the parent context. This allows a command to work below36another command and store its own information there without having to be38afraid of messing up the state of the parent command.37afraid of altering up the state of the parent command.3839Because the parent data is available, however, it is possible to navigate to40it if needed.4143Most of the time you don't see the context object, but when writing more42Most of the time, you do not see the context object, but when writing more43complex applications it comes in handy. This brings us to the next point.4445Calling Convention46``````````````````
11 unmodified lines
5859Building a Git Clone60--------------------6163In this example we want to build a command line tool that resembles a62In this example, we want to build a command line tool that resembles a63version control system. Systems like Git usually provide one64over-arching command that already accepts some parameters and65configuration, and then have extra subcommands that do other things.66
3 unmodified lines
70At 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.7375For this command we also want to accept some parameters that configure the74For this command, we also want to accept some parameters that configure the75state of our tool:7677.. click:example::78
16 unmodified lines
95 ctx.obj = Repo(repo_home, debug)969798So let's understand what this does. We create a group command which can100have subcommands. When it is invoked it will create an instance of a99have subcommands. When it is invoked, it will create an instance of a100``Repo`` class. This holds the state for our command line tool. In this102case it just remembers some parameters, but at this point it could also101case, it just remembers some parameters, but at this point it could also102start loading configuration files and so on.103104This state object is then remembered as :attr:`~Context.obj` on the105context. This is a special attribute where commands are supposed to
36 unmodified lines
142````````````````````143144While not relevant for the particular program we want to build, there is145also quite good support for interleaving systems. Imagine for instance that147there would be this super cool plugin for our version control system that148needs a lot of configuration and wants to store its own configuration as146there was a super cool plugin for our version control system that needed a147lot of configuration and wanted to store its own configuration as148:attr:`~Context.obj`. If we would then attach another command below that,149we would all of a sudden get the plugin configuration instead of our repo150object.151
68 unmodified lines
modified:docs/documentation.rst+2 added-2 removed
27 unmodified lines
28.. click:run::2930 invoke(hello, args=['--help'])3132Arguments cannot be documented this way. This is to follow general33convention of Unix tools using arguments for only the most necessary32Arguments cannot be documented this way. This is to follow the general33convention of Unix tools of using arguments for only the most necessary34things and to document them in the introduction text by referring to them35by name.3637Preventing Rewrapping
91 unmodified lines
modified:docs/index.rst+1 added-1 removed
1Welcome to the Click Documentation2==================================34click is a Python package for creating beautiful command line interfaces4Click is a Python package for creating beautiful command line interfaces5in a composable way with as little amount of code as necessary. It's the6"Command Line Interface Creation Kit". It's highly configurable but comes7with good defaults out of the box.8
88 unmodified lines
modified:docs/options.rst+27 added-27 removed
10 unmodified lines
11-------------------1213The most basic option is a value option. These options accept one14argument which is a value. If no type is provided, the type of the default15value is used. If no default value is provided the type is assumed to be15value is used. If no default value is provided, the type is assumed to be16:data:`STRING`. By default, the name of the parameter is the first long17option defined; otherwise the first short one is used.1819.. click:example::
34 unmodified lines
5455Multiple Options56----------------5758Similar to ``nargs`` there is also the case where you sometimes want to59support a parameter to be provided multiple times to and have all values60recorded and not just the last one. For instance ``git commit -m foo -m61bar`` would record two lines for the commit message. ``foo`` and ``bar``.62This can be accomplished with the ``multiple`` flag:58Similarly to ``nargs``, there is also the case of wanting to support a59parameter being provided multiple times to and have all values recorded --60not just the last one. For instance, ``git commit -m foo -m bar`` would61record two lines for the commit message: ``foo`` and ``bar``. This can be62accomplished with the ``multiple`` flag:6364Example:6566.. click:example::
11 unmodified lines
7879Counting80--------8182In some very rare circumstances, it's interesting to use the repetition82In some very rare circumstances, it is interesting to use the repetition83of options to count an integer up. This can be used for verbosity flags,84for instance:8586.. click:example::
60 unmodified lines
147.. click:run::148149 invoke(info, args=['--shout'])150151Note that if a slash is contained in your option already (for instance if152you use Windows-style parameters where ``/`` is the prefix character you153can alternatively split the parameters through ``;`` instead):151Note that if a slash is contained in your option already (for instance, if152you use Windows-style parameters where ``/`` is the prefix character), you153can alternatively split the parameters through ``;`` instead:154155.. click:example::156157 @click.command()
38 unmodified lines
196197Choice Options198--------------199200Sometimes you want to have a parameter be a choice of a list of values.200Sometimes, you want to have a parameter be a choice of a list of values.201In that case you can use :class:`Choice` type. It can be instantiated202with a list of valid values.203204Example:
19 unmodified lines
224225Prompting226---------227228Sometimes, you want parameters that can be provided from the command line,229but if not, ask for user input. This can be implemented with click by230defining a prompt string.228In 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.231232Example:233234.. click:example::
58 unmodified lines
293294Callbacks and Eager Options295---------------------------296297Sometimes you want a parameter to completely change the execution flow.297Sometimes, you want a parameter to completely change the execution flow.298For instance, this is the case when you want to have a ``--version``299parameter that prints out the version and then exits the application.300301In such cases you need two concepts: eager parameters and a callback. An302eager parameter is a parameter that is handled before others and a301In such cases, you need two concepts: eager parameters and a callback. An302eager parameter is a parameter that is handled before others, and a303callback is what executes after the parameter is handled. The eagerness304is necessary so that an earlier required parameter does not produce an305error message. For instance if ``--version`` was not eager and a305error message. For instance, if ``--version`` was not eager and a306parameter ``--foo`` was required and defined before, you would need to307specify it for ``--version`` to work. For more information see307specify it for ``--version`` to work. For more information, see308:ref:`callback-evaluation-order`.309310A callback is a function that is invoked with two parameters: the current311:class:`Context` and the value. The context provides some useful features
15 unmodified lines
327 expose_value=False, is_eager=True)328 def hello():329 click.echo('Hello World!')330331The `expose_value` parameter prevents the now pretty pointless ``version``332parameter to be passed to the callback. If that was not specified, a331The `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 set on the context if click wants to parse the command line335without and destructive behavior that would change the execution flow. In336this case, because we would exit the program, we instead do nothing.
153 unmodified lines
490491Other Prefix Characters492-----------------------493494Click can deal with alternative prefix characters, other than ``-`` for494Click 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 to498POSIX semantics. However in certain situations this can be useful:
32 unmodified lines
531532Range Options533-------------534535A special mention should go to the :class:`IntRange` type which works very536similar to the :data:`INT` type but restricts the value to fall into a535A special mention should go to the :class:`IntRange` type, which works very536similarly to the :data:`INT` type, but restricts the value to fall into a537specific range (inclusive on both edges). It has two modes:538539- the default mode (non-clamping mode) where a value that falls outside540 of the range will cause an error.
29 unmodified lines
570------------------------571572.. versionchanged:: 2.0573574If you want to apply custom validation logic you can do this in the574If 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/parameters.rst+13 added-13 removed
2 unmodified lines
34.. currentmodule:: click56Click supports two types of parameters for scripts: options and arguments.7There is generally some confusion among authors of command line scripts8when to use which so here is a quick overview of the differences. As the9name indicates an option is optional. While arguments can be optional10within reason they are much more restricted in how they can be optional.7There is generally some confusion among authors of command line scripts of8when to use which, so here is a quick overview of the differences. As its9name indicates, an option is optional. While arguments can be optional10within reason, they are much more restricted in how optional they can be.1112To help you decide between options and arguments, the recommendation is13to use arguments exclusively for things like going to subcommands or input14filenames / URLs and have everything else be an option instead.14filenames / URLs, and have everything else be an option instead.1516Differences17-----------18
56 unmodified lines
75---------------7677Parameters (both options and arguments) accept a number of positional78arguments which are the parameter declarations. Each string with a79single dash is added as short argument, each string starting with a double80dash as long one. If a string is added without any dashes it's the79single dash is added as short argument; each string starting with a double80dash as long one. If a string is added without any dashes, it becomes the81internal parameter name which is also used as variable name.8283If a parameter is not given a name without dashes a name is generated83If a parameter is not given a name without dashes, a name is generated84automatically by taking the longest argument and converting all dashes to85underscores. So for an option with ``('-f', '--foo-bar')`` the parameter86name is `foo_bar`. For an option with ``('-x',)`` the parameter is `x`.87For an option with ``('-f', '--filename', 'dest')`` the parameter is85underscores. For an option with ``('-f', '--foo-bar')``, the parameter86name is `foo_bar`. For an option with ``('-x',)``, the parameter is `x`.87For an option with ``('-f', '--filename', 'dest')``, the parameter is88called `dest`.8990Implementing Custom Types91-------------------------9293To implement a custom type, you need to subclass the :class:`ParamType`94class. Types can be invoked with or without context and parameter object94class. Types can be invoked with or without context and parameter object,95which is why they need to be able to deal with this.9697The following code implements an integer type that accepts hex and octal98numbers in addition to normal integers and converts them into regular98numbers in addition to normal integers, and converts them into regular99integers::100101 import click102
18 unmodified lines
modified:docs/prompts.rst+4 added-4 removed
1 unmodified line
2==================34.. currentmodule:: click56Click supports prompts in two different places. One is automated prompts7when the parameter handling happens. The second option is to ask for6Click supports prompts in two different places. The first is automated7prompts when the parameter handling happens, and the second is to ask for8prompts at a later point independently.910This can be accomplished with the :func:`prompt` function which asks for11valid input according to a type or the :func:`confirm` function which asks10This can be accomplished with the :func:`prompt` function, which asks for11valid input according to a type, or the :func:`confirm` function, which asks12for confirmation (yes/no).1314Option Prompts15--------------
32 unmodified lines
modified:docs/python3.rst+9 added-9 removed
14 unmodified lines
1516Python 3 Limitations17--------------------1819At the moment click suffers from a few problems on 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.21* 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.25
2 unmodified lines
28 surrogate escapes. This will not be fixed in click itself!2930 For more information see :ref:`python3-surrogates`.3132* Standard input and output on Python 3 is opened in unicode mode by32* Standard input and output on Python 3 is opened in Unicode mode by33 default. Click has to reopen the stream in binary mode in certain34 situations. Because there is no standardized way to do this, this35 might not always work. Primarily this can become a problem when36 testing command-line applications.
26 unmodified lines
63* ``sys.stdin``, ``sys.stdout``, and ``sys.stderr`` are opened in binary64 mode, but under some circumstances they support Unicode output. Click65 attempts to not subvert this but provides support for forcing streams66 to be Unicode-based.67* ``sys.argv`` is always bytes-based. Click will pass bytes to all67* ``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 APIs
6 unmodified lines
78 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.
8 unmodified lines
95Python 3 Surrogate Handling96---------------------------9798Click on Python 3 does all the Unicode handling in the standard library99and is subject to its behavior. On Python 2 click does all the Unicode100handling itself which means there are differences in error behavior.99and is subject to its behavior. On Python 2, click does all the Unicode100handling itself, which means there are differences in error behavior.101102The most glaring difference is that on Python 2, Unicode will "just work",103but requires extra care on Python 3. The reason for this is that on103while on 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 by108init systems (sysvinit, upstart, systemd, etc.), deployment tools (salt,109puppet) or cron jobs (cron) will refuse to work unless a Unicode locale is109puppet), 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 know
41 unmodified lines
modified:docs/quickstart.rst+1 added-1 removed
124 unmodified lines
125multiple subcommands that can be attached with :meth:`Group.add_command`.126127For simple scripts, it's also possible to automatically attach and create a128command by using the :meth:`Group.command` decorator instead. The above129script can be written like this then:129script can instead be written like this:130131.. click:example::132133 @click.group()
30 unmodified lines
modified:docs/setuptools.rst+4 added-4 removed
1 unmodified line
23Usage with Setuptools4=====================56When writing command line utilities it's recommended to write them as6When writing command line utilities, it's recommended to write them as7modules that are distributed with setuptools instead of using UNIX8shebangs. There are a bunch of reasons for this.8shebangs. There are many reasons for this.910The first one is that setuptools automatically generates executable11wrappers for Windows so your command line utilities work on Windows too.12
4 unmodified lines
1718Introduction19------------2021All you need to do to bundle your scripts with setuptools is your script22in a Python package and a ``setup.py`` file.21To bundle your script with setuptools, all you need is the script in a Python22package and a ``setup.py`` file.2324Imagine this directory structure::2526 yourpackage/
55 unmodified lines
modified:docs/testing.rst+5 added-5 removed
5 unmodified lines
6For basic testing, click provides the :mod:`click.testing` module which7provides test functionality that helps you invoke command line8applications and check their behavior.910These tools really only should be used for testing as they are changing11the whole interpreter state for simplicity and they are not in any way12thread safe!10These tools should really only be used for testing as they change11the entire interpreter state for simplicity and are not in any way12thread-safe!1314Basic Testing15-------------16
1 unmodified line
18: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.2122The return value is a :class:`Result` object which has the captured output23data, exit code and optional exception attached.22The return value is a :class:`Result` object, which has the captured output23data, exit code, and optional exception attached.2425Example::2627 import click
63 unmodified lines
modified:docs/upgrading.rst+4 added-4 removed
10 unmodified lines
11Upgrading to 2.012----------------1314Click 2.0 has one breaking change which is the signature for parameter15callbacks. Before 2.0 the callback was invoked with ``(ctx, value)``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 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` argument43here would be `None` so a compatibility callback could not use that42Note 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+41 added-41 removed
9 unmodified lines
1011Printing to Stdout12------------------1314The most obvious helper is the :func:`echo` function which in many ways14The most obvious helper is the :func:`echo` function, which in many ways15works like the Python print statement or function. The main difference is16that it works the same on Python 2 and 3 and it intelligently detects17misconfigured output streams and will never fail (except on Python 3, for16that it works the same on Python 2 and 3, it intelligently detects17misconfigured output streams, and will never fail (except on Python 3; for18more information see :ref:`python3-limitations`).1920Example::21
1 unmodified line
2324 click.echo('Hello World!')2526Most importantly, it can print both Unicode and binary data, unlike the27builtin ``print`` function on Python 3 which cannot output any bytes. It27builtin ``print`` function on Python 3, which cannot output any bytes. It28will, however, emit a trailing newline by default which needs to be29supressed by passing ``nl=False``::3031 click.echo(b'\xe2\x98\x83', nl=False)
5 unmodified lines
37-----------3839.. versionadded:: 2.04041Starting with click 2.0 the :func:`echo` function gained extra42functionality to deal with ANSI colors and styles. Note that on Windows41Starting 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.44is installed, then ANSI codes are intelligently handled.4546Primarily this means that:4748- click's echo function will automatically strip ANSI color codes if the
2 unmodified lines
51 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::58To install `colorama`, run this command::5960 $ pip install colorama6162For styling a string the :func:`style` function can be used::
18 unmodified lines
81-------------8283In some situations, you might want to show long texts on the terminal and84let a user scroll through it. This can be achieved by using the85:func:`echo_via_pager` function which works similar to the :func:`echo`86function but always writes to stdout and, if possible, through a pager.85:func:`echo_via_pager` function which works similarly to the :func:`echo`86function, but always writes to stdout and, if possible, through a pager.8788Example:8990.. click:example::
8 unmodified lines
99---------------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: it103To clear the terminal screen, you can use the :func:`clear` function that104is provided starting with click 2.0. It does what the name suggests: it105clears the entire visible screen in a platform-agnostic way:106107::108
5 unmodified lines
114--------------------------------115116.. versionadded:: 2.0117118Normally when reading input from the terminal you would use reading from118Normally, when reading input from the terminal, you would read from119standard 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 being122written.121to do that and instead read individual characters as they are being written.122124For this click provides the :func:`getchar` function which reads a single123For thi,s 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.
11 unmodified lines
139 click.echo('Abort!')140 else:141 click.echo('Invalid input :(')142144Note that this reads raw input which means that things like arrow keys143Note that this reads raw input, which means that things like arrow keys144will show up in the platform's native escape format. The only characters145translated are ``^C`` and ``^D`` which are converted into keyboard146interrupt and end of file exceptions. This is done because otherwise it's147too easy to forget about that and to create scripts that cannot be
4 unmodified lines
152---------------------153154.. versionadded:: 2.0155157Sometimes it's useful to pause until the user presses any key on the158keyboard. This is especially useful on Windows where ``cmd.exe`` by159default will close the window at the end of the command execution instead156Sometimes, it's useful to pause until the user presses any key on the157keyboard. This is especially useful on Windows where ``cmd.exe`` will158close the window at the end of the command execution by default, instead159of waiting.160162In click this can be accomplished by the :func:`pause` function. This161In click, this can be accomplished with the :func:`pause` function. This162function will print a quick message to the terminal (which can be164customized) and wait for the user to press a key. In addition to that165it will also become a noop if the script is not run interactively.163customized) and wait for the user to press a key. In addition to that,164it will also become a NOP (no operation instruction) if the script is not165run interactively.166167Example::168169 import click
7 unmodified lines
177178Click supports launching editors automatically through :func:`edit`. This179is very useful for asking users for multi-line input. It will180automatically open the user's defined editor or fall back to a sensible181default. If the user closes the editor without saving the return value181default. If the user closes the editor without saving, the return value182will be `None` otherwise the entered text.183184Example usage::185
20 unmodified lines
206.. versionadded:: 2.0207208Click supports launching applications through :func:`launch`. This can be209used to open the default application assocated with a URL or filetype.210This for instance can be used to launch web browsers, picture viewers, etc.211In addition to that, it can also launch the file manager and automatically210This can be used to launch web browsers or picture viewers, for instance.211In addition to this, it can also launch the file manager and automatically212select the provided file.213214Example usage::215
4 unmodified lines
220Printing Filenames221------------------222223Because filenames might not be Unicode, formatting them can be a bit224tricky. Generally this is easier on Python 2 than on 3 as you can just225write the bytes to stdout with the print function, but at least on Python2263 you will need to always operate in Unicode.224tricky. Generally, this is easier on Python 2 than on 3, as you can just225write the bytes to stdout with the print function, but on Python 3, you will226always need to operate in Unicode.227228The way this works with click is through the :func:`format_filename`229function. It does a best effort conversion of the filename to Unicode and229function. It does a best-effort conversion of the filename to Unicode and230will never fail. This makes it possible to use these filenames in the231context of a full Unicode string.232233Example::
5 unmodified lines
239----------------240241For command line utilities, it's very important to get access to input and242output streams reliably. Python generally provides access to these243streams through ``sys.stdout`` and friends, but unfortunately there are244API differences between 2.x and 3.x. Especially in regards to how these245streams respond to Unicode and binary data there are wide differences.243streams through ``sys.stdout`` and friends, but unfortunately, there are244API differences between 2.x and 3.x, especially with regards to how these245streams respond to Unicode and binary data.246247Because of this, click provides the :func:`get_binary_stream` and248:func:`get_text_stream` which produce consistent results with different249Python versions and for widely misconfigured terminals.248:func:`get_text_stream` functions, which produce consistent results with249different Python versions and for a wide variety pf terminal configurations.250251The end result is that these functions will always return a functional252stream object (except in very odd cases on Python 3, see252stream object (except in very odd cases on Python 3; see253:ref:`python3-limitations`).254255Example::256
7 unmodified lines
264---------------------------265266.. versionadded:: 2.0267268Very often you want to open a configuration file that belongs to your268Very often, you want to open a configuration file that belongs to your269application. However, different operating systems store these configuration270files in different locations depending on their standards. Click provides271a :func:`get_app_dir` function which returns the most appropriate location272for per-user config files for your application depending on the OS.
21 unmodified lines
294---------------------295296.. versionadded:: 2.0297298Sometimes you have command line scripts that need to process a lot of data298Sometimes, you have command line scripts that need to process a lot of data,299but you want to quickly show the user some progress about how long that300will take. Click supports simple progress bar rendering for that through301the :func:`progressbar` function.302
3 unmodified lines
306307 for user in all_the_users_to_process:308 modify_the_user(user)309310To hook this up with an automatically updating progress bar all you need310To hook this up with an automatically updating progress bar, all you need311to do is to change the code to this::312313 import click314
2 unmodified lines
317 modify_the_user(user)318319Click will then automatically print a progress bar to the terminal and320calculate the remaining time for you. The calculation of remaining time321requires that the iterable has a length. If it does not have a length,321requires that the iterable has a length. If it does not have a length322but you know the length, you can explicitly provide it::323324 with click.progressbar(all_the_users_to_process,325 length=number_of_users) as bar:
11 unmodified lines
modified:docs/why.rst+4 added-3 removed
87 unmodified lines
88support 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 aims92to support fully composable command line user interfaces by doing this:92to support fully composable command line user interfaces by doing the93following:9495- Click does not just parse, it also dispatches to the appropriate code.96- Click has a strong concept of an invocation context that allows97 subcommands to respond to data from the parent command.
11 unmodified lines
109 will automatically benefit from this.110111The aim of click is to make composable systems, whereas the aim of docopt112is to build the most beautiful and hand-crafted command line interfaces.112These two goals are conflicting with each other in subtle ways. Click113These 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 on116reformatting your help pages for instance.117
12 unmodified lines
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.133133In 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.137138
14 unmodified lines