是否有一种更惯用的方法使用Python获取参数列表';点击?

是否有一种更惯用的方法使用Python获取参数列表';点击?,python,python-click,Python,Python Click,我可以写以下内容: 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() 这似乎有效,至少如果我将其保存为f

我可以写以下内容:

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()
这似乎有效,至少如果我将其保存为
fun.py
我可以运行:

$ 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']

有没有一种更惯用的方法来使用Click编写此代码,或者几乎就是这样?

我认为您需要的是参数的“multiple”选项。例如

import click

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

if __name__ == '__main__':
    fun()
然后要传递多个值,需要多次指定
thing
。像这样:

$ 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')

(注意,我不是一个点击用户,所以对我说的任何话都要三缄其口)——根据文档。所以我认为这个策略是非常理想的。显然,如果你打算经常使用这个,那么一个适当命名的助手比
lambda
要好。您也可以使用
multiple=True
来支持
python fun.py--thing penguin--thing knights…
,但这会改变命令行结构。我考虑过采用这种方法并以某种方式拆分/连接列表。不过,我不确定这对我是否有效?在我看来,这也与此相关。取舍是,因为它使用参数,所以单击不会自动格式化帮助中的
--things