1

I am using python-click and I would like to pass values with a format like this

myprogram mycommand --parameter param1=value1 --parameter param2=value2

I was looking at click option documentation but I can't find any construct that could help with this, the only solution I can find is invoking a callback function and check that the string is properly constructed <key>=<value>, then elaborate the values properly.

Nothing bad in that solution, but I was wondering if there is a more elegant way to handle this since the pattern looks to be common enough.

1 Answer 1

2

So, I've had a go at it. I've managed to do it the following ways.

Firstly, I've tried this, though it doesn't satisfy the --parameter criteria.

@click.command("test")
@click.argument("args", nargs=-1)
def test(args):
    args = dict([arg.split("=") for arg in args])
    print(args)

so when invoking like test param1=test1 param2=test the output is:

{'param1': 'test1', 'param2': 'test2' }

Secondly, I thought about a multiple option, combined with a variadic argument, which seems to be closer to your requirements: test -p param1=test -p param2=test

@click.command("test")
@click.option('-p', '--parameter', multiple=True)
@click.argument("args", nargs=-1)
def test(*args, **kwargs):
    param_args = kwargs['parameter']
    param_args = dict([p.split('=') for p in param_args])
    print(param_args)


if __name__ == '__main__':
    test()

The output will be the same as the previous case.

If you were to print(kwargs['parameter']), you'd get

('param1=test', 'param2=test')

It sounds a bit more cleaner than using a callback, but not by much. Still, hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.