4

I can write the following:

import click


@click.command()
@click.option('--things', callback=lambda _,__,x: x.split(',') if x else [])
def fun(things):
    print('You gave me these things: {}'.format(things))


if __name__ == '__main__':
    fun()

This appears to work, at least if I save it as fun.py I can run:

$ python fun.py
You gave me these things: []
$ python fun.py --things penguins,knights,"something different"
You gave me these things: ['penguin', 'knights', 'something different']

Is there a more idiomatic way to write this code using Click, or is that pretty much it?

Wayne Werner
  • 49,299
  • 29
  • 200
  • 290
  • 3
    (caveat, I'm not a click user so take anything I say with a huge grain of salt) -- According to the documentation, ["only a fixed number of arguments is supported"](http://click.pocoo.org/5/options/#multi-value-options). So I think this strategy is pretty optimal. Obviously, if you're going to use this a lot then a suitably named helper is nicer than the `lambda`. You can also do `multiple=True` to support `python fun.py --thing penguin --thing knights ...`, but that changes the commandline structure. – mgilson Nov 28 '16 at 23:16
  • I've thought about taking that approach and somehow splitting/concatenating the lists. Not sure if that would work well for me, though. – Wayne Werner Nov 28 '16 at 23:28
  • http://click.pocoo.org/5/options/#multi-value-options ? – Tom Dalton Nov 29 '16 at 00:38
  • It looks to me like [this answer](http://stackoverflow.com/a/40749912/1286571) is relevant here too. The trade off is that because it uses arguments, click won't automatically format `--things` in help. – ForeverWintr Dec 10 '16 at 00:17

1 Answers1

4

What I think you want is the 'multiple' option for parameters. E.g.

import click

@click.command()
@click.option('--thing', multiple=True)
def fun(thing):
    print('You gave me these things: {}'.format(thing))

if __name__ == '__main__':
    fun()

And then to pass multiple values, you specify thing multiple times. Like so:

$ python fun.py
You gave me these things: ()

$ python fun.py --thing me
You gave me these things: ('me',)

$ python fun.py --thing penguins --thing knights --thing "something different"
You gave me these things: ('penguins', 'knights', 'something different')
MinchinWeb
  • 631
  • 1
  • 9
  • 18