Skip to content
Myr

Added example on ignoring of unknown options.

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

authored by Armin Ronacher · committed by Armin Ronacher · parent da0132f · Browse files · 3 files+124 added−4 removed
This commit

State

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

Diff stats

3 files+124 added−4 removed

  • other:+124 added−4 removed

3 files+124 added−4 removed

modified:click/core.py+7 added-2 removed
106 unmodified lines
107 Added the `allow_extra_args` and `allow_interspersed_args`108 parameters.109110 .. versionadded:: 4.0111 Added the `color` parameter.111 Added the `color` and `ignore_unknown_options` parameter.112113 :param command: the command class for this context.114 :param parent: the parent context.115 :param info_name: the info name for this invokation. Generally this
379 unmodified lines
495 :param name: the name of the command to use unless a group overrides it.496 :param context_settings: an optional dictionary with defaults that are497 passed to the context object.498 """499 #: the default for the :attr:`Context.allow_extra_args` flag.500 allow_extra_args = False501 #: the default for the :attr:`Context.allow_interspersed_args` flag.502 allow_interspersed_args = True503 #: the default for the :attr:`Context.ignore_unknown_options` flag.504 ignore_unknown_options = False505506 def __init__(self, name, context_settings=None):507 #: the name the command thinks it has. Upon registering a command508 #: on a :class:`Group` the group will default the command name509 #: with this information. You should instead use the510 #: :class:`Context`\'s :attr:`~Context.info_name` attribute.511 self.name = name512 if context_settings is None:513 context_settings = {}514 #: an optional dictionary with defaults passed to the context.515 self.context_settings = context_settings516517 def get_usage(self, ctx):
16 unmodified lines
534 :param parent: the parent context if available.535 :param extra: extra keyword arguments forwarded to the context536 constructor.537 """533 for key, value in iteritems(self.context_settings or {}):538 for key, value in iteritems(self.context_settings):539 if key not in extra:540 extra[key] = value541 ctx = Context(self, info_name=info_name, parent=parent, **extra)542 self.parse_args(ctx, args)
1070 unmodified lines
modified:docs/advanced.rst+95 added
241 unmodified lines
242 default to values from a parameter that came before.243244Most of the time you do not need to be concerned about any of this,245but it is important to know how it works for some advanced cases.246247.. _forwarding-unknown-options:248249Forwarding Unknown Options250--------------------------251252In some situations it is interesting to be able to accept all unknown253options for further manual processing. Click can generally do that as of254Click 4.0, but it has some limitations that lie in the nature of the255problem. The support for this is provided through a parser flag called256``ignore_unknown_options`` which will instruct the parser to collect all257unknown options and to put them to the leftover argument instead of258triggering a parsing error.259260This can generally be activated in two different ways:2612621. It can be enabled on custom :class:`Command` subclasses by changing263 the :attr:`~BaseCommand.ignore_unknown_options` attribute.2642. It can be enabled by changing the attribute of the same name on the265 context class (:attr:`Context.ignore_unknown_options`). This is best266 changed through the ``context_settings`` dictionary on the command.267268For most situations the easiest solution is the second. Once the behavior269is changed something needs to pick up those leftover options (which at270this point are considered arguments). For this again you have two271options:2722731. You can use :func:`pass_context` to get the context passed. This will274 only work if in addition to :attr:`~Context.ignore_unknown_options`275 you also set :attr:`~Context.allow_extra_args` as otherwise the276 command will abort with an error that there are leftover arguments.277 If you go with this solution, the extra arguments will be collected in278 :attr:`Context.args`.2792. You can attach a :func:`argument` with ``nargs`` set to `-1` which280 will eat up all leftover arguments. In this case it's recommeded to281 set the `type` to :data:`UNPROCESSED` to avoid any string processing282 on those arguments as otherwise they are forced into unicode strings283 automatically which is often not what you want.284285In the end you end up with something like this:286287.. click:example::288289 import sys290 from subprocess import call291292 @click.command(context_settings=dict(293 ignore_unknown_options=True,294 ))295 @click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode')296 @click.argument('timeit_args', nargs=-1, type=click.UNPROCESSED)297 def cli(verbose, timeit_args):298 """A wrapper around Python's timeit."""299 cmdline = ['python', '-mtimeit'] + list(timeit_args)300 if verbose:301 click.echo('Invoking: %s' % ' '.join(cmdline))302 call(cmdline)303304And what it looks like:305306.. click:run::307308 invoke(cli, prog_name='cli', args=['--help'])309 println()310 invoke(cli, prog_name='cli', args=['-n', '100', 'a = 1; b = 2; a * b'])311 println()312 invoke(cli, prog_name='cli', args=['-v', 'a = 1; b = 2; a * b'])313314As you can see the verbosity flag is handled by Click, everything else315ends up in the `timeit_args` variable for further processing which then316for instance, allows invoking a subprocess. There are a few things that317are important to know about how this ignoring of unhandled flag happens:318319* Unknown long options are generally ignored and not processed at all.320 So for instance if ``--foo=bar`` or ``--foo bar`` are passed they321 generally end up like that. Note that because the parser cannot know322 if an option will accept an argument or not, the ``bar`` part might be323 handled as an argument.324* Unknown short options might be partially handled and reassmebled if325 necessary. For instance in the above example there is an option326 called ``-v`` which enables verbose mode. If the command would be327 ignored with ``-va`` then the ``-v`` part would be handled by Click328 (as it is known) and ``-a`` would end up in the leftover parameters329 for further processing.330* Depending on what you plan on doing you might have some success by331 disabling interspersed arguments332 (:attr:`~Context.allow_interspersed_args`) which instructs the parser333 to not allow arguments and options to be mixed. Depending on your334 situation this might improve your results.335336Generally though the combinated handling of options and arguments from337your own commands and commands from another application are discouraged338and if you can avoid it, you should. It's a much better idea to have339everything below a subcommand be forwarded to another application than to340handle some arguments yourself.
modified:docs/clickdoctools.py+22 added-2 removed
2 unmodified lines
3import click4import shutil5import tempfile6import contextlib7import subprocess89try:10 from StringIO import StringIO11except ImportError:
38 unmodified lines
50 return iter(self._echo(x) for x in self._input)515253@contextlib.contextmanager54def fake_modules():55 old_call = subprocess.call56 def dummy_call(*args, **kwargs):57 with tempfile.TemporaryFile('wb+') as f:58 kwargs['stdout'] = f59 kwargs['stderr'] = f60 rv = subprocess.Popen(*args, **kwargs).wait()61 f.seek(0)62 click.echo(f.read().decode('utf-8', 'replace').rstrip())63 return rv64 subprocess.call = dummy_call65 try:66 yield67 finally:68 subprocess.call = old_call697071@contextlib.contextmanager72def isolation(input=None, env=None):73 if isinstance(input, unicode):74 input = input.encode('utf-8')75 input = StringIO(input or '')
65 unmodified lines
141 '__file__': 'dummy.py',142 }143144 def declare(self, source):145 with fake_modules():126 code = compile(source, '<docs>', 'exec')127 eval(code, self.namespace)146 code = compile(source, '<docs>', 'exec')147 eval(code, self.namespace)148149 def run(self, source):150 code = compile(source, '<docs>', 'exec')151 buffer = []
124 unmodified lines