advanced.rst
This file
Path
docs/advanced.rst
381 lines · 14.0 KiB
Last changed by
Merge pull request #1331 from chusband/GH-1042David Lordbefore adoption68c9328
History of this fileTake it
The walk stopped after 200 commits: lines older than 430c50a point at it.
Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a
lines 1–14why, one step back1Advanced Patterns2=================34.. currentmodule:: click56In addition to common functionality that is implemented in the library7itself, there are countless patterns that can be implemented by extending8Click. This page should give some insight into what can be accomplished.910.. _aliases:1112Command Aliases13---------------14Merge pull request #1331 from chusband/GH-1042David Lordbefore adoption68c9328
lines 15–19why, one step back15Many tools support aliases for commands (see `Command alias example16<https://github.com/pallets/click/tree/master/examples/aliases>`_).17For instance, you can configure ``git`` to accept ``git ci`` as alias for18``git commit``. Other tools also support auto-discovery for aliases by19automatically shortening them.Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a
lines 20–299why, one step back2021Click does not support this out of the box, but it's very easy to customize22the :class:`Group` or any other :class:`MultiCommand` to provide this23functionality.2425As explained in :ref:`custom-multi-commands`, a multi command can provide26two methods: :meth:`~MultiCommand.list_commands` and27:meth:`~MultiCommand.get_command`. In this particular case, you only need28to override the latter as you generally don't want to enumerate the29aliases on the help page in order to avoid confusion.3031This following example implements a subclass of :class:`Group` that32accepts a prefix for a command. If there were a command called ``push``,33it would accept ``pus`` as an alias (so long as it was unique):3435.. click:example::3637 class AliasedGroup(click.Group):3839 def get_command(self, ctx, cmd_name):40 rv = click.Group.get_command(self, ctx, cmd_name)41 if rv is not None:42 return rv43 matches = [x for x in self.list_commands(ctx)44 if x.startswith(cmd_name)]45 if not matches:46 return None47 elif len(matches) == 1:48 return click.Group.get_command(self, ctx, matches[0])49 ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))5051And it can then be used like this:5253.. click:example::5455 @click.command(cls=AliasedGroup)56 def cli():57 pass5859 @cli.command()60 def push():61 pass6263 @cli.command()64 def pop():65 pass6667Parameter Modifications68-----------------------6970Parameters (options and arguments) are forwarded to the command callbacks71as you have seen. One common way to prevent a parameter from being passed72to the callback is the `expose_value` argument to a parameter which hides73the parameter entirely. The way this works is that the :class:`Context`74object has a :attr:`~Context.params` attribute which is a dictionary of75all parameters. Whatever is in that dictionary is being passed to the76callbacks.7778This can be used to make up addition parameters. Generally this pattern79is not recommended but in some cases it can be useful. At the very least80it's good to know that the system works this way.8182.. click:example::8384 import urllib8586 def open_url(ctx, param, value):87 if value is not None:88 ctx.params['fp'] = urllib.urlopen(value)89 return value9091 @click.command()92 @click.option('--url', callback=open_url)93 def cli(url, fp=None):94 if fp is not None:95 click.echo('%s: %s' % (url, fp.code))9697In this case the callback returns the URL unchanged but also passes a98second ``fp`` value to the callback. What's more recommended is to pass99the information in a wrapper however:100101.. click:example::102103 import urllib104105 class URL(object):106107 def __init__(self, url, fp):108 self.url = url109 self.fp = fp110111 def open_url(ctx, param, value):112 if value is not None:113 return URL(value, urllib.urlopen(value))114115 @click.command()116 @click.option('--url', callback=open_url)117 def cli(url):118 if url is not None:119 click.echo('%s: %s' % (url.url, url.fp.code))120121122Token Normalization123-------------------124125.. versionadded:: 2.0126127Starting with Click 2.0, it's possible to provide a function that is used128for normalizing tokens. Tokens are option names, choice values, or command129values. This can be used to implement case insensitive options, for130instance.131132In order to use this feature, the context needs to be passed a function that133performs the normalization of the token. For instance, you could have a134function that converts the token to lowercase:135136.. click:example::137138 CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower())139140 @click.command(context_settings=CONTEXT_SETTINGS)141 @click.option('--name', default='Pete')142 def cli(name):143 click.echo('Name: %s' % name)144145And how it works on the command line:146147.. click:run::148149 invoke(cli, prog_name='cli', args=['--NAME=Pete'])150151Invoking Other Commands152-----------------------153154Sometimes, it might be interesting to invoke one command from another155command. This is a pattern that is generally discouraged with Click, but156possible nonetheless. For this, you can use the :func:`Context.invoke`157or :func:`Context.forward` methods.158159They work similarly, but the difference is that :func:`Context.invoke` merely160invokes another command with the arguments you provide as a caller,161whereas :func:`Context.forward` fills in the arguments from the current162command. Both accept the command as the first argument and everything else163is passed onwards as you would expect.164165Example:166167.. click:example::168169 cli = click.Group()170171 @cli.command()172 @click.option('--count', default=1)173 def test(count):174 click.echo('Count: %d' % count)175176 @cli.command()177 @click.option('--count', default=1)178 @click.pass_context179 def dist(ctx, count):180 ctx.forward(test)181 ctx.invoke(test, count=42)182183And what it looks like:184185.. click:run::186187 invoke(cli, prog_name='cli', args=['dist'])188189190.. _callback-evaluation-order:191192Callback Evaluation Order193-------------------------194195Click works a bit differently than some other command line parsers in that196it attempts to reconcile the order of arguments as defined by the197programmer with the order of arguments as defined by the user before198invoking any callbacks.199200This is an important concept to understand when porting complex201patterns to Click from optparse or other systems. A parameter202callback invocation in optparse happens as part of the parsing step,203whereas a callback invocation in Click happens after the parsing.204205The main difference is that in optparse, callbacks are invoked with the raw206value as it happens, whereas a callback in Click is invoked after the207value has been fully converted.208209Generally, the order of invocation is driven by the order in which the user210provides the arguments to the script; if there is an option called ``--foo``211and an option called ``--bar`` and the user calls it as ``--bar212--foo``, then the callback for ``bar`` will fire before the one for ``foo``.213214There are three exceptions to this rule which are important to know:215216Eagerness:217 An option can be set to be "eager". All eager parameters are218 evaluated before all non-eager parameters, but again in the order as219 they were provided on the command line by the user.220221 This is important for parameters that execute and exit like ``--help``222 and ``--version``. Both are eager parameters, but whatever parameter223 comes first on the command line will win and exit the program.224225Repeated parameters:226 If an option or argument is split up on the command line into multiple227 places because it is repeated -- for instance, ``--exclude foo --include228 baz --exclude bar`` -- the callback will fire based on the position of229 the first option. In this case, the callback will fire for230 ``exclude`` and it will be passed both options (``foo`` and231 ``bar``), then the callback for ``include`` will fire with ``baz``232 only.233234 Note that even if a parameter does not allow multiple versions, Click235 will still accept the position of the first, but it will ignore every236 value except the last. The reason for this is to allow composability237 through shell aliases that set defaults.238239Missing parameters:240 If a parameter is not defined on the command line, the callback will241 still fire. This is different from how it works in optparse where242 undefined values do not fire the callback. Missing parameters fire243 their callbacks at the very end which makes it possible for them to244 default to values from a parameter that came before.245246Most of the time you do not need to be concerned about any of this,247but it is important to know how it works for some advanced cases.248249.. _forwarding-unknown-options:250251Forwarding Unknown Options252--------------------------253254In some situations it is interesting to be able to accept all unknown255options for further manual processing. Click can generally do that as of256Click 4.0, but it has some limitations that lie in the nature of the257problem. The support for this is provided through a parser flag called258``ignore_unknown_options`` which will instruct the parser to collect all259unknown options and to put them to the leftover argument instead of260triggering a parsing error.261262This can generally be activated in two different ways:2632641. It can be enabled on custom :class:`Command` subclasses by changing265 the :attr:`~BaseCommand.ignore_unknown_options` attribute.2662. It can be enabled by changing the attribute of the same name on the267 context class (:attr:`Context.ignore_unknown_options`). This is best268 changed through the ``context_settings`` dictionary on the command.269270For most situations the easiest solution is the second. Once the behavior271is changed something needs to pick up those leftover options (which at272this point are considered arguments). For this again you have two273options:2742751. You can use :func:`pass_context` to get the context passed. This will276 only work if in addition to :attr:`~Context.ignore_unknown_options`277 you also set :attr:`~Context.allow_extra_args` as otherwise the278 command will abort with an error that there are leftover arguments.279 If you go with this solution, the extra arguments will be collected in280 :attr:`Context.args`.2812. You can attach a :func:`argument` with ``nargs`` set to `-1` which282 will eat up all leftover arguments. In this case it's recommended to283 set the `type` to :data:`UNPROCESSED` to avoid any string processing284 on those arguments as otherwise they are forced into unicode strings285 automatically which is often not what you want.286287In the end you end up with something like this:288289.. click:example::290291 import sys292 from subprocess import call293294 @click.command(context_settings=dict(295 ignore_unknown_options=True,296 ))297 @click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode')298 @click.argument('timeit_args', nargs=-1, type=click.UNPROCESSED)299 def cli(verbose, timeit_args):Merge pull request #963 from lamby/895270-python-click-please-make-the-build-reproducibleDavid Lordbefore adoption288a00a
lines 300–301why, one step back300 """A fake wrapper around Python's timeit."""301 cmdline = ['echo', 'python', '-mtimeit'] + list(timeit_args)Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a
lines 302–325why, one step back302 if verbose:303 click.echo('Invoking: %s' % ' '.join(cmdline))304 call(cmdline)305306And what it looks like:307308.. click:run::309310 invoke(cli, prog_name='cli', args=['--help'])311 println()312 invoke(cli, prog_name='cli', args=['-n', '100', 'a = 1; b = 2; a * b'])313 println()314 invoke(cli, prog_name='cli', args=['-v', 'a = 1; b = 2; a * b'])315316As you can see the verbosity flag is handled by Click, everything else317ends up in the `timeit_args` variable for further processing which then318for instance, allows invoking a subprocess. There are a few things that319are important to know about how this ignoring of unhandled flag happens:320321* Unknown long options are generally ignored and not processed at all.322 So for instance if ``--foo=bar`` or ``--foo bar`` are passed they323 generally end up like that. Note that because the parser cannot know324 if an option will accept an argument or not, the ``bar`` part might be325 handled as an argument.fix typo reassmebled => reassembled (#884)jacobtolarbefore adoption763f3eb
line 326why, one step back326* Unknown short options might be partially handled and reassembled ifMerge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a
lines 327–381why, one step back327 necessary. For instance in the above example there is an option328 called ``-v`` which enables verbose mode. If the command would be329 ignored with ``-va`` then the ``-v`` part would be handled by Click330 (as it is known) and ``-a`` would end up in the leftover parameters331 for further processing.332* Depending on what you plan on doing you might have some success by333 disabling interspersed arguments334 (:attr:`~Context.allow_interspersed_args`) which instructs the parser335 to not allow arguments and options to be mixed. Depending on your336 situation this might improve your results.337338Generally though the combinated handling of options and arguments from339your own commands and commands from another application are discouraged340and if you can avoid it, you should. It's a much better idea to have341everything below a subcommand be forwarded to another application than to342handle some arguments yourself.343344345Global Context Access346---------------------347348.. versionadded:: 5.0349350Starting with Click 5.0 it is possible to access the current context from351anywhere within the same thread through the use of the352:func:`get_current_context` function which returns it. This is primarily353useful for accessing the context bound object as well as some flags that354are stored on it to customize the runtime behavior. For instance the355:func:`echo` function does this to infer the default value of the `color`356flag.357358Example usage::359360 def get_current_command_name():361 return click.get_current_context().info_name362363It should be noted that this only works within the current thread. If you364spawn additional threads then those threads will not have the ability to365refer to the current context. If you want to give another thread the366ability to refer to this context you need to use the context within the367thread as a context manager::368369 def spawn_thread(ctx, func):370 def wrapper():371 with ctx:372 func()373 t = threading.Thread(target=wrapper)374 t.start()375 return t376377Now the thread function can access the context like the main thread would378do. However if you do use this for threading you need to be very careful379as the vast majority of the context is not thread safe! You are only380allowed to read from the context, but not to perform any modifications on381it.