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.
Python **kwargs In the function, we use the double asterisk ** before the parameter name to denote this type of argument. The arguments are passed as a dictionary and these arguments make a dictionary inside function with name same as the parameter excluding double asterisk ** .
First of all, let me tell you that it is not necessary to write *args or **kwargs. Only the * (asterisk) is necessary. You could have also written *var and **vars. Writing *args and **kwargs is just a convention.
“ kwargs ” stands for keyword arguments. It is used for passing advanced data objects like dictionaries to a function because in such functions one doesn't have a clue about the number of arguments, hence data passed is be dealt properly by adding “**” to the passing type.
*args specifies the number of non-keyworded arguments that can be passed and the operations that can be performed on the function in Python whereas **kwargs is a variable number of keyworded arguments that can be passed to a function that can perform dictionary operations.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With