Add unspecified options to cli command using pytho

2019-01-15 14:56发布

问题:

I would like to add unspecified options to the cli command using python-click library. So my cli function could look like the following

$ my-cmd --option1 value1 --options2 value2 --unknown_var value3

My current code:

import click

@click.option('--option1')
@click.option('--option2')
@click.command(name='my-cmd')
def cli(option1, option2):
  click.echo("my test")

I would like to see something like the following:

import click

@click.option('--option1')
@click.option('--option2')
@click.command(name='my-cmd')
def cli(option1, option2, **kwargs):
  click.echo("my test")
  # Manually manage **kwargs

回答1:

You can pass context with ignore_unknown_options and allow_extra_args settings, the extra arguments will be collected in context.args list (['--unknown_var', 'value3', '--unknown_var2', 'value4']). Then you can transform it to dict.

import click

@click.command(name='my-cmd', context_settings=dict(
    ignore_unknown_options=True,
    allow_extra_args=True,
))
@click.option('--option1')
@click.option('--option2')
@click.pass_context
def cli(ctx, option1, option2):
    click.echo({ctx.args[i][2:]: ctx.args[i+1] for i in xrange(0, len(ctx.args), 2)})

example

python cli.py --option1 value1 --option2 value2 --unknown_var value3 --unknown_var2 value4
>> {'unknown_var2': 'value4', 'unknown_var': 'value3'}

See Forwarding Unknown Options.