3

我可以写以下内容:

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 编写此代码,或者仅此而已?

4

1 回答 1

2

我认为您想要的是参数的“多个”选项。例如

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')
于 2017-01-24T23:04:39.693 回答