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
Provenance
- Commit
4851f7c- Tree
0cd9d40- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
da0132f
3 files changed+124 added−4 removed
modified:click/core.py+7 added-2 removed
106 unmodified lines107 Added the `allow_extra_args` and `allow_interspersed_args`108 parameters.109 110 .. versionadded:: 4.0111- Added the `color` parameter.111+ Added the `color` and `ignore_unknown_options` parameter.112 113 :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 this379 unmodified lines495 :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 = False505 506 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_settings516 517 def get_usage(self, ctx):16 unmodified lines534 :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 linesmodified:docs/advanced.rst+95 added
241 unmodified lines242 default to values from a parameter that came before.243 244 Most of the time you do not need to be concerned about any of this,245 but it is important to know how it works for some advanced cases.246+247+.. _forwarding-unknown-options:248+249+Forwarding Unknown Options250+--------------------------251+252+In some situations it is interesting to be able to accept all unknown253+options for further manual processing. Click can generally do that as of254+Click 4.0, but it has some limitations that lie in the nature of the255+problem. The support for this is provided through a parser flag called256+``ignore_unknown_options`` which will instruct the parser to collect all257+unknown options and to put them to the leftover argument instead of258+triggering a parsing error.259+260+This can generally be activated in two different ways:261+262+1. It can be enabled on custom :class:`Command` subclasses by changing263+ the :attr:`~BaseCommand.ignore_unknown_options` attribute.264+2. 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.267+268+For most situations the easiest solution is the second. Once the behavior269+is changed something needs to pick up those leftover options (which at270+this point are considered arguments). For this again you have two271+options:272+273+1. 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`.279+2. 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.284+285+In the end you end up with something like this:286+287+.. click:example::288+289+ import sys290+ from subprocess import call291+292+ @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)303+304+And what it looks like:305+306+.. click:run::307+308+ 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'])313+314+As you can see the verbosity flag is handled by Click, everything else315+ends up in the `timeit_args` variable for further processing which then316+for instance, allows invoking a subprocess. There are a few things that317+are important to know about how this ignoring of unhandled flag happens:318+319+* 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.335+336+Generally though the combinated handling of options and arguments from337+your own commands and commands from another application are discouraged338+and if you can avoid it, you should. It's a much better idea to have339+everything below a subcommand be forwarded to another application than to340+handle some arguments yourself.modified:docs/clickdoctools.py+22 added-2 removed
2 unmodified lines3 import click4 import shutil5 import tempfile6 import contextlib7+import subprocess8 9 try:10 from StringIO import StringIO11 except ImportError:38 unmodified lines50 return iter(self._echo(x) for x in self._input)51 52 53 @contextlib.contextmanager54+def 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_call69+70+71+@contextlib.contextmanager72 def isolation(input=None, env=None):73 if isinstance(input, unicode):74 input = input.encode('utf-8')75 input = StringIO(input or '')65 unmodified lines141 '__file__': 'dummy.py',142 }143 144 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)148 149 def run(self, source):150 code = compile(source, '<docs>', 'exec')151 buffer = []124 unmodified lines