Search code examples
pythondictionarykeyword-argumentpython-click

Python click pass unspecified number of kwargs


Recently discovered click and I would like to pass an unspecified number of kwargs to a click command. Currently this is my command:

@click.command()
@click.argument('tgt')
@click.argument('fun')
@click.argument('args', nargs=-1)
def runner(tgt, fun, args):
    req = pyaml.p(meh.PostAdapter(tgt, fun, *args))
    click.echo(req)

However when using nargs anything more than 1 is passed as a tuple ([docs][1]) and I cannot type=dict that unfortunately.

But it should be possible to do something like this:

command positional1 positional2 foo='bar' baz='qux' xxx='yyy'

Thanks in advance for any help or suggestions, in the meantime I will keep chipping away at this myself.


Solution

  • Using the link that @rmn provided, I rewrote my click command as follows:

    @click.command(context_settings=dict(
        ignore_unknown_options=True,
        allow_extra_args=True,
    ))
    @click.pass_context
    def runner(ctx, tgt, fun):
        d = dict()
        for item in ctx.args:
            d.update([item.split('=')])
        req = pyaml.p(meh.PostAdapter(tgt, fun, d))
        click.echo(req)
    

    Which allows me to issue the following command properly:

    mycmd tgt fun foo='bar' baz='qux' xxx='yyy'