有没有更惯用的方法来使用Python的Click来获取args列表?

时间:2016-11-28 23:08:02

标签: 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()

这似乎有效,至少我将其保存为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编写此代码是否有更惯用的方式,或者就是这样吗?

1 个答案:

答案 0 :(得分:1)

我认为你想要的是参数的'倍数'选项。 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()

然后要传递多个值,请多次指定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')