Skip to content
Myr

Merge pull request #109 from iKevinY/doc-fixes

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

Documentation Fixes

authored by Armin Ronacher · committed by Armin Ronacher · parents 1b9e2c0, 98910c1 · Browse files · 16 files+289 added−291 removed
This commit

State

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

Diff stats

16 files+289 added−291 removed

  • other:+289 added−291 removed

16 files+289 added−291 removed

modified:docs/advanced.rst+18 added-18 removed
11 unmodified lines
1213Command Aliases14---------------1516Many tools support aliases for commands. For instance you can configure16Many tools support aliases for commands. For instance, you can configure17``git`` to accept ``git ci`` as alias for ``git commit``. Other tools18also support auto discovery for aliases by automatically shortening them.1920Click does not support this out of the box but it's very easy to customize21the :class:`Group` or any other :class:`MultiCommand` to provide this22functionality.2324As explained in :ref:`custom-multi-commands` a multi command can provide24As 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 need27to override the latter as you generally don't want to enumerate the28aliases on the help page to avoid confusion.2930This following example implements a subclass of :class:`Group` that31accepts a prefix for a command. So if there is a command called32``push`` it would accept ``pus`` as alias if it's unique:31accepts a prefix for a command. If there is a command called32``push`` it would accept ``pus`` as an alias if it's unique:3334.. click:example::3536 class AliasedGroup(click.Group):
9 unmodified lines
46 elif len(matches) == 1:47 return click.Group.get_command(self, ctx, matches[0])48 ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))4950And it can be used like this then:50And it can then be used like this:5152.. click:example::5354 @click.command(cls=AliasedGroup)
10 unmodified lines
6566Invoking Other Commands67-----------------------6869Sometimes it might be interesting to invoke one command from another70command. This is generally a pattern that is discouraged with click but69Sometimes, 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`72or :func:`Context.forward` methods.7374They work similar but the difference is that :func:`Context.invoke` merely74They work similarly, but the difference is that :func:`Context.invoke` merely75invokes another command with the arguments you provide as a caller,76whereas :func:`Context.forward` fills in the arguments from the current77command. Both accept the command as first argument and everything else is78passed onwards as you would expect.77command. Both accept the command as the first argument and everything else78is passed onwards as you would expect.7980Example:8182.. click:example::
37 unmodified lines
120The 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 user125provides the arguments to the script. So if there is an option called126``--foo`` and an option called ``--bar`` and the user calls it as ``--bar127--foo`` then the callback for ``bar`` will fire before the one for ``foo``.124Generally, the order of invocation is driven by the order in which the user125provides the arguments to the script; if there is an option called ``--foo``126and an option called ``--bar`` and the user calls it as ``--bar127--foo``, then the callback for ``bar`` will fire before the one for ``foo``.128129There are two exceptions to this rule which are important to know:130131Eagerness:
1 unmodified line
133 evaluated before all non-eager parameters, but again in the order as134 they were provided on the command line by the user.135136 This is important for parameters that execute and exit like ``--help``137 and ``--version``. Both are eager parameters but whatever parameter137 and ``--version``. Both are eager parameters, but whatever parameter138 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 of144 the first option. So in this case the callback will fire for143 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.148
2 unmodified lines
151 value except the first. The reason for this is to allow composability152 through shell aliases that set defaults.153154Missing parameters:155 If a parameter is not defined on the command line the callback will155 If a parameter is not defined on the command line, the callback will156 still fire. This is different from how it works in optparse where157 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.
3 unmodified lines
modified:docs/arguments.rst+24 added-24 removed
67 unmodified lines
6869 If you come from ``argparse`` you might be missing support for setting70 ``nargs`` to ``+`` to indicate that at least one argument is required.7172 This is supported by setting ``required=True``. However this should72 This is supported by setting ``required=True``. However, this should73 not be used if you can avoid it as we believe scripts should gracefully74 degrade into becoming noops if a variadic argument is empty. The75 reason for this is that very often scripts are invoked with wildcard75 reason for this is that very often, scripts are invoked with wildcard76 inputs from the command line and they should not error out if the77 wildcard is empty.7879.. _file-args:8081File Arguments82--------------8384Since all the examples have already worked with file names it makes sense84Since 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 bytes90intelligently handles files for you. It also deals with Unicode and bytes91correctly for all versions of Python so your script stays very portable.9293Example:94
27 unmodified lines
122will 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.125126Instead you should be using the :class:`Path` type which handles this127complexity for you. Not only will it return either bytes or unicode126Instead, 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.130131Example:
23 unmodified lines
155The :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 files159user 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.162163This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` to164the constructor. If the file is openened lazily it will fail on first IO164the constructor. If the file is opened lazily, it will fail on first IO165operation by raising an :exc:`FileError`.166167Since files opened for writing will typically immediatley empty the file,168the lazy mode should really only be disabled if the developer is 100% sure167Since files opened for writing will typically immediately empty the file,168the lazy mode should only be disabled if the developer is absolutely sure169that this is intended behavior.170171Forcing on lazy mode is also very useful to avoid resource handling172confusion. If a file is opened in lazy mode it will get a173``close_intelligently`` method that can help you figuring out if the file174needs closing or not. This is not needed for parameters, but it is171Forcing lazy mode is also very useful to avoid resource handling172confusion. If a file is opened in lazy mode, it will receive a173``close_intelligently`` method that can help figure out if the file174needs closing or not. This is not needed for parameters, but is175necessary for manually prompting with the :func:`prompt` function as you176do not know if a stream like stdout was openend (which was already open176do 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 by180passing ``atomic=True``. In atomic mode all writes go into a separate180passing ``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.184185Environment Variables186---------------------187188Like options, arguments can also get values from an environment variable.189Unlike options however this is only supported for explicitly named189Unlike options, however, this is only supported for explicitly named190environment variables.191192Example usage:193
12 unmodified lines
206 with open('hello.txt', 'w') as f:207 f.write('Hello World!')208 invoke(echo, env={'SRC': 'hello.txt'})209210In that case it can also be a list of different environment variables210In 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.215216Arguments looking like Options216Arguments-Like Options217------------------------------218219Sometimes you want to process arguments that look like options. For220instance imagine you have a file named ``-foo.txt``. If you pass this as221such as an argument click will treat it as an option.220instance, 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 does223To 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 as225arguments. After the ``--`` marker, all further parameters are accepted as226arguments.227228Example usage:229
13 unmodified lines
modified:docs/bashcomplete.rst+13 added-13 removed
1 unmodified line
2=============34.. versionadded:: 2.056Starting with click 2.0 there is built-in support for bash completion for6As 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.8is available, but for the most part it should just work.910Limitations11-----------1213Bash completion is only available if a script has been installed properly14and not executed through the ``python`` command. For information about15how to do that see :ref:`setuptools-integration`. Currently click also15how 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>29 clone commit copy delete setuser 29 clone commit copy delete setuser30 $ repo clone -<TAB><TAB>31 --deep --help --rev --shallow -r 31 --deep --help --rev --shallow -r3233Activation34----------3536In order to activate bash completion you need to inform bash that36In 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``39through a magic environment variable called ``_<PROG_NAME>_COMPLETE``,40where ``<PROG_NAME>`` is your application executable name in uppercase41with dashes replaced by underscores.4243So if your tool is called ``foo-bar`` then the magic variable is called43If your tool is called ``foo-bar``, then the magic variable is called44``_FOO_BAR_COMPLETE``. By exporting it with the ``source`` value it will45spit out the activation script which can be trivally activated.4647For instance to enable bash completion for your ``foo-bar`` script, this47For instance, to enable Bash completion for your ``foo-bar`` script, this48is 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 systems60ship 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+34 added-35 removed
8 unmodified lines
910Callback Invocation11-------------------1213For a regular command the callback is executed whenever the command runs.14So if the script is the only command it will always fire (unless a15parameter callback prevents it. This for instance happens if someone13For a regular command, the callback is executed whenever the command runs.14If 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 that case18For groups and multi commands, the situation looks different. In this case,19the callback fires whenever a subcommand fires (unless this behavior is20changed). What this means in practice is that an outer command runs21when an inner command runs:22
18 unmodified lines
4142Nested Handling and Contexts43----------------------------4445As you can see from the earlier example the basic command group accepts a45As you can see from the earlier example, the basic command group accepts a46debug argument which is passed to its callback, but not to the sync47command itself. The sync command only accepts its own arguments.4849This allows tools to act completely independent of each other. But how49This allows tools to act completely independent of each other, but how50does one command talk to a nested one? The answer to this is the51:class:`Context`.5253Each time a command is invoked a new context is created and linked with the54parent context. Normally you can't see these contexts, but they are53Each time a command is invoked, a new context is created and linked with the54parent context. Normally, you can't see these contexts, but they are55there. Contexts are passed to parameter callbacks together with the56value automatically. Commands can also ask for the context to be passed57by marking themselves with the :func:`pass_context` decorator. In that58case the context is passed as first argument.58case, the context is passed as first argument.5960The context can also carry a program specified object that can be61used for the program's purposes. What this means is that you can build a62script like this:
13 unmodified lines
7677 if __name__ == '__main__':78 cli(obj={})7980If the object is provided each context will pass the object onwards to80If the object is provided, each context will pass the object onwards to81its children, but at any level a context's object can be overridden. To82reach to a parent ``context.parent`` can be used.82reach to a parent, ``context.parent`` can be used.8384In addition to that instead of passing an object down nothing stops the85application from modifying global state. For instance you could just flip84In addition to that, instead of passing an object down, nothing stops the85application from modifying global state. For instance, you could just flip86a global ``DEBUG`` variable and be done with it.8788Decorating Commands89-------------------9091As you have seen in the earlier example a decorator can change how a91As you have seen in the earlier example, a decorator can change how a92command is invoked. What actually happens behind the scenes is that93callbacks are always invoked through the :meth:`Context.invoke` method94which automatically invokes a command correctly (by either passing the95context or not).9697This is very useful when you want to write custom decorators. For98instance a common pattern would be to configure an object representing98instance, a common pattern would be to configure an object representing99state and then storing it on the context and then to use a custom100decorator to find the most recent object of this sort and pass it as first101argument.102103For instance the :func:`pass_obj` decorator can be implemented like this:103For instance, the :func:`pass_obj` decorator can be implemented like this:104105.. click:example::106107 from functools import update_wrapper
4 unmodified lines
112 return ctx.invoke(f, ctx.obj, *args, **kwargs)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,116in the correct way, so the function will either be called with ``f(ctx,117obj)`` or ``f(obj)`` depending on if it itself is decorated with118:func:`with_context`.119120This is a very powerful context that can be used to build very complex
2 unmodified lines
123124Group Invocation Without Command125--------------------------------126127By default a group or multi command is not invoked unless a subcommand is127By default, a group or multi command is not invoked unless a subcommand is128passed. In fact, not providing a command automatically passes ``--help``129by default. This behavior can be changed by passing130``invoke_without_command=True`` to a group. In that case the callback is130``invoke_without_command=True`` to a group. In that case, the callback is131always invoked instead of showing the help page. The context object also132includes information about if the invocation would go to a subcommand or133not.132includes information about whether or not the invocation would go to a133subcommand.134135Example:136137.. click:example::
11 unmodified lines
149 click.echo('The subcommand')150151And how it works in practice::152153 $ python tool.py 153 $ python tool.py154 I was invoked without subcommand155 $ python tool.py sync156 I am about to invoke sync157 The subcommand
2 unmodified lines
160161Custom Multi Commands162---------------------163164In addition to using :func:`click.group` you can also build your own164In addition to using :func:`click.group`, you can also build your own165custom multi commands. This is useful when you want to support commands166being loaded lazily from plugins.167168A custom multi command just needs to implement a list and load method:
39 unmodified lines
208209Merging Multi Commands210----------------------211212In addition to implementing custom multi commands it can also be212In 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 nesting 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 the218:class:`CommandCollection` class. It accepts a list of other multi219commands and makes the commands available on the same class. It accepts a220list of other multi commands and makes the commands available on the same221level.219commands and makes the commands available on the same level.220221Example usage:222223.. click:example::
26 unmodified lines
250.. click:run::251252 invoke(cli, prog_name='cli', args=['--help'])253256In case a command exists on more than one source, the first source wins.254In case a command exists in more than one source, the first source wins.255256Overriding Defaults257-------------------258261By default the default value for a parameter is pulled from the262``default`` flag that is provided when it's defined. But that's not the259By default, the default value for a parameter is pulled from the260``default`` flag that is provided when it's defined, but that's not the261only place defaults can be loaded from. The other place is the262:attr:`Context.default_map` (a dictionary) on the context. This allows265defaults to be loaded from a config file to override the regular defaults.263defaults to be loaded from a configuration file to override the regular264defaults.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 be271provided when the script is invoked. Alternatively it can also be272overriden at any point by commands. For instance a toplevel command could273load the defaults from a config file.270provided when the script is invoked. Alternatively, it can also be271overriden at any point by commands. For instance a top-level command could272load the defaults from a configuration file.273274Example usage:275276.. click:example::
26 unmodified lines
modified:docs/complex.rst+53 added-52 removed
3 unmodified lines
4====================56.. currentmodule:: click78Click is designed to write complex and simple CLI tools alike. However9the power of its design is the ability to arbitrarily nest systems10together. For instance in case you have ever used Django you will have11realized that it provides a command line utility. But so does Celery for12instance. So when using Celery with Django there are two tools that need8Click 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.1415In a theoretical world of two separate click command line utilities they16can solve this problem by nesting one inside the other. For instance the16can solve this problem by nesting one inside the other. For instance, the17web framework could also load the commands for the message queue18framework.1920Basic Concepts
4 unmodified lines
2526Contexts27````````2829Whenever a click command is executed a :class:`Context` object is created30which holds state for this particular invocation. For instance it31remembers parsed parameters, what command created it, which resources need32to be cleaned up at the end of the function and so forth. It also holds33an application defined object optionally.29Whenever a click command is executed, a :class:`Context` object is created30which holds state for this particular invocation. It remembers parsed31parameters, what command created it, which resources need to be cleaned up32at the end of the function, and so forth. It can also optionally hold an33application-defined object.3435Context objects build a linked list until they hit top one. Each context36is linked to the parent context. This allows a command to work below37another command and store its own information there without having to be38afraid of messing up the state of the parent command.3940Because the parent data is however available it's possible to navigate to40Because the parent data is available, however, it is possible to navigate to41it if needed.4243Most of the time you don't see the context object, but when writing more44complex applications it comes in handy. This brings us to the next point.4546Calling Convention47``````````````````4849When a click command callback is executed it's passed all the non hidden50parameters as keyword arguments. Notably absent is the context. However51a callback can opt-into being passed the context object by marking itself49When a click command callback is executed, it's passed all the non-hidden50parameters as keyword arguments. Notably absent is the context. However,51a callback can opt into being passed the context object by marking itself52with :func:`pass_context`.5354So how do you invoke a command callback if you don't know if it should55receive the context or not? The answer is that the context itself56provides a helper function (:meth:`Context.invoke`) which can do this for57you. It accepts the callback as first argument and then invokes the58function correctly.5960Building a Git61--------------60Building a Git Clone61--------------------6263In this example we want to build a command line tool that resembles a64version control system a bit. Systems like git usually provide one64version control system. Systems like Git usually provide one65over-arching command that already accepts some parameters and66configuration, and then has extra subcommands that do other things.66configuration, and then have extra subcommands that do other things.6768The Root Command69````````````````7071At the top level we need a group that can hold all our commands. In this72case we use the basic :func:`click.group` which allows us to register71At the top level, we need a group that can hold all our commands. In this72case, we use the basic :func:`click.group` which allows us to register73other click commands below it.7475For this command we also want to accept some parameters that configure the76state of our tool:
21 unmodified lines
9899So let's understand what this does. We create a group command which can100have subcommands. When it is invoked it will create an instance of a101``Repo`` class. This holds the state for our command line tool. In this102case it just remembers some parameters but at this point it could also103start loading config files and so on.102case it just remembers some parameters, but at this point it could also103start loading configuration files and so on.104105This state object is then remembered as :attr:`~Context.obj` on the106context. This is a special attribute where commands are supposed to107remember what they need to pass on to their children.108109In order for this to work we need to mark our function with110:func:`pass_context` because otherwise the context object would be109In order for this to work, we need to mark our function with110:func:`pass_context`, because otherwise the context object would be111entirely hidden from us.112113The First Child Command114```````````````````````115116So let's add our first child command to it. Let's go with the clone117command:116Let's add our first child command to it, the clone command:117118.. click:example::119120 @cli.command()
2 unmodified lines
123 def clone(src, dest):124 pass125126So now we have a clone command, but how do we get access to the repo? As128you can imagine one way is to use the :func:`pass_context` function which127you can imagine, one way is to use the :func:`pass_context` function which128again will make our callback also get the context passed on which we130memorized the repo. Even better there is a second version of this131decorator called :func:`pass_obj` which will just pass the stored object,132in our case the repo:129memorized the repo. However, there is a second version of this decorator130called :func:`pass_obj` which will just pass the stored object, (in our case131the repo):132133.. click:example::134135 @cli.command()
5 unmodified lines
141142Interleaved Commands143````````````````````144146While not relevant for this particular program we want to build there is147also quite good support for interleaving systems. Imagine for instance145While not relevant for the particular program we want to build, there is146also 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 as149:attr:`~Context.obj`. If we would then attach another command below that,151all the sudden we would get the plugin config instead of our repo object.150we would all of a sudden get the plugin configuration instead of our repo151object.152153One obvious way is to store a reference to the repo on the plugin but then154a command needs to be aware that it's attached below such a plugin.153One obvious way to remedy this is to store a reference to the repo in the154plugin, but then a command needs to be aware that it's attached below such a155plugin.156156There is a much better system by taking advantage of the linked nature of157contexts. We know that the plugin context is linked to the context that158created our repo. Because of that we can start a search for the last157There is a much better system that can built by taking advantage of the linked158nature of contexts. We know that the plugin context is linked to the context159that created our repo. Because of that, we can start a search for the last160level where the object stored on the context was a repo.161162Built-in support for this is provided by the :func:`make_pass_decorator`162factory which will create decorators for us that find objects (it163internally calls into :meth:`Context.find_object`). So in our case we164know that we want to find the closest ``Repo`` object. So let's make a163factory, which will create decorators for us that find objects (it164internally calls into :meth:`Context.find_object`). In our case, we165know that we want to find the closest ``Repo`` object, so let's make a166decorator for this:167168.. click:example::169170 pass_repo = click.make_pass_decorator(Repo)171171If we now use ``pass_repo`` instead of ``pass_obj`` we will always get a172If we now use ``pass_repo`` instead of ``pass_obj``, we will always get a173repo instead of something else:174175.. click:example::176
3 unmodified lines
180 @pass_repo181 def clone(repo, src, dest):182 pass183183Ensuring Objects184````````````````184Ensuring Object Creation185````````````````````````186187The above example only works if there was an outer command that created a188``Repo`` object and stored it on the context. For some more advanced use188cases this might be a problem for you. The default behavior of189:func:`make_pass_decorator` is to call into :meth:`Context.find_object`190which will find the object. If it can't find the object it will raise an189cases, this might become a problem. The default behavior of190:func:`make_pass_decorator` is to call :meth:`Context.find_object`191which will find the object. If it can't find the object, it will raise an192error. The alternative behavior is to use :meth:`Context.ensure_object`192which will find the object, or if it cannot find it, will create one and193which will find the object, and if it cannot find it, will create one and194store it on the innermost context. This behavior can also be enabled for195:func:`make_pass_decorator` by passing ``ensure=True``:196197.. click:example::198199 pass_repo = click.make_pass_decorator(Repo, ensure=True)200200In this case the innermost context gets such an object created if it's201In this case, the innermost context gets an object created if it is202missing. This might replace objects being placed there earlier. In this202case the command stays executable, even if the outer command does not run.203For this to work the object type needs to have a constructor that accepts203case, the command stays executable, even if the outer command does not run.204For this to work, the object type needs to have a constructor that accepts205no arguments.206207As such it runs standalone:208
12 unmodified lines
modified:docs/documentation.rst+15 added-15 removed
1Documenting Scripts2===================34Click makes it very easy to document your command line tools. First of5all it automatically generates help pages for you. While these are6currently not customizable in layout, all the texts can be changed.5all, it automatically generates help pages for you. While these are6currently not customizable in layout, all of the text can be changed.78Help Texts9----------1011Commands and options accept help arguments. In case of commands the doc11Commands and options accept help arguments. In the case of commands, the doc12string of the function is automatically used if provided.1314Simple example:15
13 unmodified lines
2930 invoke(hello, args=['--help'])3132Arguments cannot be documented this way. This is to follow general33convention of Unix tools to use arguments only for the most necessary33convention of Unix tools using arguments for only the most necessary34things and to document them in the introduction text by referring to them35by name.3637Preventing Rewrapping38---------------------3940The default behavior of click is to rewrap text to work correctly for the41width of the terminal. In some circumstances this can become a problem.41width of the terminal. In some circumstances, this can become a problem.42The main issue is showing code examples where newlines are significant.4344Rewrapping can be disabled on a per-paragraph case by adding a line with45just the ``\b`` escape marker in it. This line will be removed from the44Rewrapping can be disabled on a per-paragraph basis by adding a line with45solely the ``\b`` escape marker in it. This line will be removed from the46help text and rewrapping will be disabled.4748Example:49
23 unmodified lines
7374 invoke(cli, args=['--help'])757677Meta Vars78---------77Meta Variables78--------------7980Options and parameters accept a ``metavar`` argument that can change the81meta variable in the help page. The default version is the parameter name82in uppercase with underscores and sometimes annotated differently if83optional. This can be customized at all levels:82in uppercase with underscores, but can be annotated differently if83desired. This can be customized at all levels:8485.. click:example::8687 @click.command(options_metavar='<options>')
9 unmodified lines
9798.. click:run::99100 invoke(hello, args=['--help'])101 101102103Command Short Help104------------------105106For commands a short help is generated. By default it's the first part107(until the first dot) of the help message of the command unless it's too108long. This can also be overridden:106For commands, a short help snippet is generated. By default, it's the first107sentence of the help message of the command, unless it's too long. This can108also be overridden:109110.. click:example::111112 @click.group()
16 unmodified lines
modified:docs/license.rst+3 added-3 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 sticks4Click is licensed under a three-clause BSD License. It basically means:5do 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 derivatives7Furthermore, you must not use the names of the authors to promote derivatives8of the software without written consent.910License Text11------------
2 unmodified lines
modified:docs/options.rst+38 added-39 removed
2 unmodified lines
34.. currentmodule:: click56Adding options to commands can be accomplished by the :func:`option`7decorator. Since options can come in various different versions there7decorator. Since options can come in various different versions, there8are a ton of parameters to configure their behavior.910Basic Value Options11-------------------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 default14argument 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 be16:data:`STRING`. The name of the parameter is by default the first long17option defined, otherwise the first short one.16:data:`STRING`. By default, the name of the parameter is the first long17option defined; otherwise the first short one is used.1819.. click:example::2021 @click.command()
12 unmodified lines
3435Multi Value Options36-------------------3738Sometimes you have options that take more than one argument. For options38Sometimes, you have options that take more than one argument. For options,39only a fixed number of arguments is supported. This can be configured by40the ``nargs`` parameter. The values are then stored as a tuple.4142.. click:example::
11 unmodified lines
5455Multiple Options56----------------5758Similar to ``nargs`` there is also the case where sometimes you want to58Similar 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:
15 unmodified lines
7879Counting80--------8182In some very rare circumstances it's interesting to use the repeating of83options to count an integer up. This for instance can be used for84verbosity flags:82In some very rare circumstances, it's interesting to use the repetition83of options to count an integer up. This can be used for verbosity flags,84for instance:8586.. click:example::8788 @click.command()
11 unmodified lines
100-------------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 string104for enabling or disabling the option. (If a slash is in an option string,105click automatically knows that it's a boolean flag and will pass106``is_flag=True`` implicitly). Click always wants you to provide an enable106``is_flag=True`` implicitly.) Click always wants you to provide an enable107and disable flag so that you can change the default later.108109Example:110
15 unmodified lines
126127 invoke(info, args=['--shout'])128 invoke(info, args=['--no-shout'])129130If you really don't want an off-switch you can just define one and130If you really don't want an off-switch, you can just define one and131manually inform click that something is a flag:132133.. click:example::134
15 unmodified lines
150151Feature Switches152----------------153154In addition to boolean flags there are also feature switches. These are155implemented by setting multiple options to the same parameter name and by156defining a flag value. Note that by providing the ``flag_value`` parameter154In addition to boolean flags, there are also feature switches. These are155implemented by setting multiple options to the same parameter name and156defining a flag value. Note that by providing the ``flag_value`` parameter,157click will implicitly set ``is_flag=True``.158159To set a default flag assign a value of `True` to the flag that should be159To set a default flag, assign a value of `True` to the flag that should be160the default.161162.. click:example::163
46 unmodified lines
210211Prompting212---------213214Sometimes you want parameters that can either be provided from the command215line or if not, you want to ask for user input. This can be implemented216with click by defining a prompt string.214Sometimes, you want parameters that can be provided from the command line,215but if not, ask for user input. This can be implemented with click by216defining a prompt string.217218Example:219220.. click:example::
9 unmodified lines
230231 invoke(hello, args=['--name=John'])232 invoke(hello, input=['John'])233234If you are not happy with the default prompt string you can ask for234If you are not happy with the default prompt string, you can ask for235a different one:236237.. click:example::238
27 unmodified lines
266.. click:run::267268 invoke(encrypt, input=['secret', 'secret'])269270Because this combination of parameters is quite common this can also be270Because this combination of parameters is quite common, this can also be271replaced with the :func:`password_option` decorator:272273.. click:example::274
5 unmodified lines
280Callbacks and Eager Options281---------------------------282283Sometimes you want a parameter to completely change the execution flow.284This for instance is the case when you want to have a ``--version``284For instance, this is the case when you want to have a ``--version``285parameter that prints out the version and then exits the application.286287In such cases you need two concepts: eager parameters and a callback. An288eager parameter is a parameter that is handled before others and a
25 unmodified lines
314 def hello():315 click.echo('Hello World!')316317The `expose_value` parameter prevents the now pretty pointless ``version``318parameter to be passed to the callback. If that was not specified a318parameter to be passed to the callback. If that was not specified, a319boolean would be passed to the `hello` script. The `resilient_parsing`320flag is set on the context if click wants to parse the command line321without and destructive behavior that would change the execution flow. In322this case because we would exit the program, we instead do nothing in that323case.322this case, because we would exit the program, we instead do nothing.323324What it looks like:325326.. click:run::
8 unmodified lines
335336Yes Parameters337--------------338340For dangerous operations it's very useful to be able to ask a user for339For dangerous operations, it's very useful to be able to ask a user for340confirmation. This can be done by adding a boolean ``--yes`` flag and341asking for confirmation if the user did not provide it and to fail in a342callback:343
16 unmodified lines
360361 invoke(dropdb, input=['n'])362 invoke(dropdb, args=['--yes'])363365Because this combination of parameters is quite common this can also be364Because this combination of parameters is quite common, this can also be365replaced with the :func:`confirmation_option` decorator:366367.. click:example::368
11 unmodified lines
380---------------------------------381382A very useful feature of click is the ability to accept parameters from383environment variables in addition to regular parameters. This allows385tools to be automated much easier. For instance you might want to pass386the config file as ``--config`` parameter but also support exporting a387``TOOL_CONFIG=hello.cfg`` key / value pair for a nicer development384tools to be automated much easier. For instance, you might want to pass385a configuration file with a ``--config`` parameter but also support exporting386a ``TOOL_CONFIG=hello.cfg`` key-value pair for a nicer development387experience.388389This is supported by click in two ways. One is to automatically build390environment variables which is supported for options only. To enable this392feature the ``auto_envvar_prefix`` parameter needs to be passed to the393script that is invoked. Each command and parameter is then added as394underscore-separated variable in uppercase. So if you have a subcommand391feature, the ``auto_envvar_prefix`` parameter needs to be passed to the392script that is invoked. Each command and parameter is then added as an393uppercase underscore-separated variable. If you have a subcommand394called ``foo`` taking an option called ``bar`` and the prefix is396``MY_TOOL`` then the variable is ``MY_TOOL_FOO_BAR``.395``MY_TOOL``, then the variable is ``MY_TOOL_FOO_BAR``.396397Example usage:398399.. click:example::
49 unmodified lines
449450The default implementation for all types is to split on whitespace. The451exceptions to this rule are the :class:`File` and :class:`Path` types452which both split according to the operating system's path splitting rules.454On UNIX systems like Linux and OS X the splitting happens for those on455every colon (``:``) and for Windows on a semicolon (``;``).453On UNIX systems like Linux and OS X, the splitting happens for those on454every colon (``:``), and for Windows, on every semicolon (``;``).455456Example usage:457458.. click:example::
49 unmodified lines
508A special mention should go to the :class:`IntRange` type which works very509similar to the :data:`INT` type but restricts the value to fall into a510specific range (inclusive on both edges). It has two modes:511513- the default mode (non clamping mode) where a value that falls outside512- the default mode (non-clamping mode) where a value that falls outside513 of the range will cause an error.514- an optional clamping mode where a value that falls outside of the515 range will be clamped. This means that a range of ``0-5`` would516 return ``5`` for the value ``10`` or ``0`` for the value ``-1`` (for
18 unmodified lines
535536 invoke(repeat, args=['--count=1000', '--digit=5'])537 invoke(repeat, args=['--count=1000', '--digit=12'])538540If you pass ``None`` for any of the edges it means that the range is open539If you pass ``None`` for any of the edges, it means that the range is open540at that side.541542Callbacks for Validation543------------------------
4 unmodified lines
548parameter callbacks. These callbacks can both modify values as well as549raise errors if the validation does not work.550551In click 1.0 you can only raise the :exc:`UsageError` but starting with553click 2.0 you can also raie the :exc:`BadParameter` error which has the552click 2.0 you can also raise the :exc:`BadParameter` error which has the553added advantage that it will automatically format the error message to554also contain the parameter name.555556Example:
25 unmodified lines
modified:docs/parameters.rst+6 added-6 removed
8 unmodified lines
9name indicates an option is optional. While arguments can be optional10within reason they are much more restricted in how they can be optional.1112To help you decide between options and arguments, the recommendation is13to use arguments exclusively for things like going to subcommands or input 13to use arguments exclusively for things like going to subcommands or input14filenames / URLs and have everything else be an option instead.1516Differences17-----------
49 unmodified lines
67.. autoclass:: IntRange68 :noindex:6970Custom parameter types can be implemented by subclassing71:class:`click.ParamType`. For simple cases passing a python function that72fails with a `ValueError` is also supported though discouraged.71:class:`click.ParamType`. For simple cases, passing a Python function that72fails with a `ValueError` is also supported, though discouraged.7374Parameter Names75---------------76
12 unmodified lines
8990Implementing Custom Types91-------------------------9293To implement a custom type you need to subclass the :class:`ParamType`93To implement a custom type, you need to subclass the :class:`ParamType`94class. Types can be invoked with or without context and parameter object95which is why they need to be able to deal with this.9697The following code implements an integer type that accepts hex, octal97The following code implements an integer type that accepts hex and octal98numbers in addition to normal integers and converts them into regular99integers::100101 import click
12 unmodified lines
114 self.fail('%s is not a valid integer' % value, param, ctx)115116 BASED_INT = BasedIntParamType()117118As you can see a subclass needs to implement the :meth:`ParamType.convert`118As you can see, a subclass needs to implement the :meth:`ParamType.convert`119method and optionally provide the :attr:`ParamType.name` attribute. The120latter can be used for documentation purposes.
modified:docs/prompts.rst+9 added-9 removed
7 unmodified lines
8prompts 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 asks12for confirmation (yes / no).12for confirmation (yes/no).1314Option Prompts15--------------1617Option prompts are integrated into the option interface. See18:ref:`option-prompting` for more information. Internally it18:ref:`option-prompting` for more information. Internally, it19automatically calls into :func:`prompt` or :func:`confirm` as necessary.2021Input Prompts22-------------2324To manually ask for user input you can use the :func:`prompt` function.25By default it accepts any unicode string but you can ask for any other24To manually ask for user input, you can use the :func:`prompt` function.25By default, it accepts any Unicode string, but you can ask for any other26type. For instance you can ask for a valid integer::2728 value = click.prompt('Please enter a valid integer', type=int)2930The type is also automatically detected if a default is provided. The31following for instance will only accept floats::30The type is also automatically detected if a default is provided. For31instance, the following will only accept floats::3233 value = click.prompt('Please enter a number', default=42.0)3435Confirmation Prompts36--------------------3738To ask if a user wants to continue with an action the :func:`confirm`39function comes in handy. By default it returns the result of the prompt40as boolean value::38To ask if a user wants to continue with an action, the :func:`confirm`39function comes in handy. By default, it returns the result of the prompt40as a boolean value::4142 if click.confirm('Do you want to continue?'):43 click.echo('Well done!')44
3 unmodified lines
modified:docs/python3.rst+23 added-23 removed
21 unmodified lines
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 unicode26 Misconfigured environments can currently cause a wide range of Unicode27 problems on Python 3 due to the lack of support for roundtripping28 surrogate escapes. This will not be fixed in click itself!2930 For more information see :ref:`python3-surrogates`.
16 unmodified lines
47 sys.stdin = io.TextIOWrapper(in_stream, encoding='utf-8')48 out_stream = io.BytesIO()49 sys.stdout = io.TextIOWrapper(out_stream, encoding='utf-8')5051 Remember that in that case you need to use ``out_stream.getvalue()``51 Remember that in that case, you need to use ``out_stream.getvalue()``52 and not ``sys.stdout.getvalue()`` if you want to access the buffer53 contents as the wrapper will not forward that method.5455Python 2 / 3 Differences55Python 2 and 3 Differences56------------------------5758Click attempts to minimize the differences between Python 2 and Python 359by following the best practices for both languages.6061On Python 2 the following is true:61On Python 2, the following is true:6263* ``sys.stdin``, ``sys.stdout``, and ``sys.stderr`` are opened in binary64 mode but under some circumstances they support unicode output. Click64 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.66 to be Unicode-based.67* ``sys.argv`` is always bytes-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.7475On Python 3 the following is true:75On 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 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.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.8384 This causes problems when the terminal is incorrectly set and Python85 does not figure out the encoding. In that case the unicode string85 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.
2 unmodified lines
9495Python 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 unicode98Click 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.101102The most glaring difference is that on Python 2 unicode will "just work"102The 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 on104Python 3 the encoding detection is done in the interpreter and on Linux104Python 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 there 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 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 know114about the state of the system once it's invoked and restore the values115before Python's unicode handling kicked in.115before Python's Unicode handling kicked in.116117If you see something like this error on Python 3::118119 Traceback (most recent call last):
3 unmodified lines
123 to Python 2 or consult for http://click.pocoo.org/python3/124 mitigation steps.125126You are dealing with an environment where Python 3 thinks you are127restricted to ASCII data. The solution for these problems is different127restricted to ASCII data. The solution to these problems is different128depending on which locale your computer is running in.129130For instance if you have a German linux machine you can fix the problem130For instance if you have a German Linux machine you can fix the problem131by exporting the locale to ``de_DE.utf-8``::132133 export LC_ALL=de_DE.utf-8134 export LANG=de_DE.utf-8135136If you are on a US machine, ``en_EN.utf-8`` is the encoding of choice. On137some newer linux systems you can also try ``C.UTF-8`` as locale::137some newer Linux systems you can also try ``C.UTF-8`` as locale::138139 export LC_ALL=C.UTF-8140 export LANG=C.UTF-8141
7 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+10 added-11 removed
38 unmodified lines
3940Basic Concepts41--------------4243Click is based on declaring commands through decorators. Internally there44is a non-decorator interface for advanced use cases but it's discouraged43Click 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 through48:func:`click.command`. In the most simple version just decorating a49function with this decorator will make it into a callable script:48:func:`click.command`. At its simplest, just decorating a function49with this decorator will make it into a callable script:5051.. click:example::5253 import click
33 unmodified lines
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
23 unmodified lines
119120 cli.add_command(initdb)121 cli.add_command(dropdb)122123As you can see the :func:`group` decorator works like the :func:`command`124decorator but creates a :class:`Group` object instead which can be given125multiple subcommands that can be attached with126:meth:`Group.add_command`.123As you can see, the :func:`group` decorator works like the :func:`command`124decorator, but creates a :class:`Group` object instead which can be given125multiple subcommands that can be attached with :meth:`Group.add_command`.126128For simple scripts it's also possible to automatically attach and create a127For 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:130131.. click:example::
12 unmodified lines
144145Adding Parameters146-----------------147149To add parameters the :func:`option` and :func:`argument` decorators:148To add parameters, use the :func:`option` and :func:`argument` decorators:149150.. click:example::151152 @click.command()
11 unmodified lines
modified:docs/setuptools.rst+3 added-3 removed
17 unmodified lines
18Introduction19------------2021All you need to do to bundle your scripts with setuptools is your script22in a python package and a ``setup.py`` file.22in a Python package and a ``setup.py`` file.2324Imagine this layout::24Imagine this directory structure::2526 yourpackage/27 cli.py28 setup.py
26 unmodified lines
55 yourscript=yourpackage.cli:cli56 ''',57 )5859The magic is in the ``entry_points`` parameter. Below ``console_scripts``59The 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 click63command.
18 unmodified lines
modified:docs/testing.rst+3 added-3 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 really only should be used for testing as they are changing
29 unmodified lines
4041File System Isolation42---------------------4344For basic command line tools that want to operate with the file system the44For basic command line tools that want to operate with the file system, the45:meth:`CliRunner.isolated_filesystem` method comes in useful which sets up46an empty folder and changes the current working directory to.4748Example::
19 unmodified lines
68Input Streams69-------------7071The test wrapper can also be used to provide input data for the input72stream (stdin). This is very useful for testing prompts for instance::72stream (stdin). This is very useful for testing prompts, for instance::7374 import click75 from click.testing import CliRunner76
14 unmodified lines
modified:docs/utils.rst+23 added-23 removed
21 unmodified lines
22 import click2324 click.echo('Hello World!')2526Most importantly it can print both unicode and binary data, unlike the26Most importantly, it can print both Unicode and binary data, unlike the27builtin ``print`` function on Python 3 which cannot output any bytes. It28will however emit a trailing newline by default which needs to be28will, however, emit a trailing newline by default which needs to be29supressed by passing ``nl=False``::3031 click.echo(b'\xe2\x98\x83', nl=False)32
46 unmodified lines
7980Pager Support81-------------8283In some situations you might want to show long texts on the terminal and83In 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.87
13 unmodified lines
101.. 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: it105clears the entire visible screen in a platform agnostic way:105clears the entire visible screen in a platform-agnostic way:106107::108109 import click
5 unmodified lines
115116.. versionadded:: 2.0117118Normally when reading input from the terminal you would use reading from119standard input. However this is buffered input and will not show up until120the line has been terminated. In certain circumstances you might not want119standard 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.123124For this click provides the :func:`getchar` function which reads a single125character from the terminal buffer and returns it as a unicode character.125character from the terminal buffer and returns it as a Unicode character.126127Note that this function will always read from the terminal, even if stdin128is instead a pipe.129
39 unmodified lines
169 message = click.edit('\n\n' + MARKER)170 if message is not None:171 return message.split(MARKER, 1)[0].rstrip('\n')172173Alternatively the function can also be used to launch editors for files by174a specific filename. In that case the return value is always `None`.173Alternatively, the function can also be used to launch editors for files by174a specific filename. In this case, the return value is always `None`.175176Example usage::177178 import click
5 unmodified lines
184185.. versionadded:: 2.0186187Click supports launching applications through :func:`launch`. This can be188used to open the default application assocated with a URL or file type.189This for instance can be used to both launch web browsers as well as190picture viewers etc. In addition to that it can also launch the file191manager and automatically select the provided file.188used to open the default application assocated with a URL or filetype.189This for instance can be used to launch web browsers, picture viewers, etc.190In addition to that, it can also launch the file manager and automatically191select the provided file.192193Example usage::194195 click.launch('http://click.pocoo.org/')
2 unmodified lines
198199Printing Filenames200------------------201202Because filenames might not be unicode, formatting them can be a bit202Because filenames might not be Unicode, formatting them can be a bit203tricky. Generally this is easier on Python 2 than on 3 as you can just204write the bytes to stdout with the print function, but at least on Python2053 you will need to always operate in unicode.2053 you will need to always operate in Unicode.206207The way this works with click is through the :func:`format_filename`208function. It does a best effort conversion of the filename to Unicode and209will never fail. This makes it possible to use these filenames in the210context of a full unicode string.210context of a full Unicode string.211212Example::213214 click.echo('Path: %s' % click.format_filename(b'foo.txt'))
1 unmodified line
216217Standard Streams218----------------219220For command line utilities it's very important to get access to input and220For command line utilities, it's very important to get access to input and221output streams reliably. Python generally provides access to these222streams through ``sys.stdout`` and friends, but unfortunately there are223API differences between 2.x and 3.x. Especially in regards to how these224streams respond to unicode and binary data there are wide differences.224streams respond to Unicode and binary data there are wide differences.225226Because of this click provides the :func:`get_binary_stream` and226Because of this, click provides the :func:`get_binary_stream` and227:func:`get_text_stream` which produce consistent results with different228Python versions and for widely misconfigured terminals.229230The end result is that these functions will always return a functional
12 unmodified lines
243---------------------------244245.. versionadded:: 2.0246247Very often you want to open a config file that belongs to your248application. However different operating systems store these config249files by their policy in different places. Click provides a250:func:`get_app_dir` function which returns the most appropriate location247Very often you want to open a configuration file that belongs to your248application. However, different operating systems store these configuration249files in different locations depending on their standards. Click provides250a :func:`get_app_dir` function which returns the most appropriate location251for per-user config files for your application depending on the OS.252253Example usage::254
61 unmodified lines
modified:docs/why.rst+14 added-14 removed
1Why Click?2==========34There are so many libraries out there for writing command line utilities,4There are so many libraries out there for writing command line utilities;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 unmodified lines
18There are many alternatives to click and you can have a look at them if19you enjoy them better. The obvious ones are ``optparse`` and ``argparse``20from the standard library.2122click is actually implemented as a wrapper around a mild fork of22Click is actually implemented as a wrapper around a mild fork of23``optparse`` and does not implement any parsing itself. The reason it's24not based on ``argparse`` is that ``argparse`` does not allow proper25nesting of commands by design and has some deficiencies when it comes to26POSIX compliant argument handling.
23 unmodified lines
50with. The reason however click is not using argparse is that it has some51problematic behaviors that make handling arbitrary command line interfaces52hard:5354* argparse has builtin magic behavior to guess if something is an54* argparse has built-in magic behavior to guess if something is an55 argument or an option. This becomes a problem when dealing with56 incomplete command lines as it's not possible to know without having a57 full understanding of the command line how the parser is going to58 behave. This goes against click's ambitions of dispatching to
13 unmodified lines
7273Docopt for instance acts by parsing your help pages and then parsing74according to those rules. The side effect of this is that docopt is quite75rigid in how it handles the command line interface. The upside of docopt76is that it gives you strong control over your help page, the downside is77that due to that it cannot rewrap your output for the current terminal76is that it gives you strong control over your help page; the downside is77that due to this it cannot rewrap your output for the current terminal78width and it makes translations hard. On top of that docopt is restricted79to basic parsing. It does not handle argument dispatching and callback80invocation or types. This means there is a lot of code that needs to be81written in addition to the basic help page to handle the parsing results.8283Most of all however it makes composability hard. While docopt does83Most of all, however, it makes composability hard. While docopt does84support dispatching to subcommands, it for instance does not directly85support any kind of automatic subcommand enumeration based on what's86available or it does not enforce subcommands to work in a consistent way.8788This is fine, but it's different from how click wants to work. Click aims89to support fully composable command line user interfaces by doing this:9091- click does not just parse, it also dispatches to the appropriate code.92- click has a strong concept of an invocation context that allows91- Click does not just parse, it also dispatches to the appropriate code.92- Click has a strong concept of an invocation context that allows93 subcommands to respond to data from the parent command.94- click has strong information available for all parameters and commands94- Click has strong information available for all parameters and commands95 so that it can generate unified help pages for the full CLI and to96 assist the user in converting the input data as necessary.97- click has strong understanding of what types are and can give the user97- Click has a strong understanding of what types are and can give the user98 consistent error messages if something goes wrong. A subcommand99 written by a different developer will not suddenly die with a100 different error messsage because it's manually handled.101- click has enough meta information available for its whole program101- Click has enough meta information available for its whole program102 that it can evolve over time to improve the user experience without103 forcing developers to adjust their programs. For instance if click103 forcing developers to adjust their programs. For instance, if click104 decides to change how help pages are formatted, all click programs105 will automatically benefit from this.106107The aim of click is to make composable systems, whereas the aim of docopt
13 unmodified lines
121it hard to achieve a consistent command line experience.122123The best example for this is optparse's ``callback`` functionality for124accepting arbitrary number of arguments. Due to syntactical ambiguities125on the command line there is no way to implement fully variadic arguments.125on the command line, there is no way to implement fully variadic arguments.126There are always tradeoffs that need to be made and in case of127``argparse`` these tradeoffs have been critical enough, that a system like128click cannot even be implemented on top of it.129
9 unmodified lines
139even optparse and argparse support automatic expansion of long arguments.140The reason for this is that it's a liability for backwards compatibility.141If people start relying on automatically modified parameters and someone142adds a new parameter in the future, the script might stop working. These143kind of problems are hard to find so click does not attempt to be magical143kinds of problems are hard to find so click does not attempt to be magical144about this.145146This sort of behavior however can be implemented on a higher level to147support things such as explicit aliases. For more information see
1 unmodified line