Skip to main content
 首页 » 编程设计

python之是否有更惯用的方法来使用 Python 的 Click 获取参数列表

2025年02月15日14sky-heaven

我可以这样写:

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 编写此代码,或者差不多就是这样?

请您参考如下方法:

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

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