6

我想知道如何覆盖click.optionClick lib)的目标变量。例如在这样一段代码中

import click

@click.command()
@click.option('--output', default='data')
def generate_data(output_folder):
    print(output_folder)

所以我想使用--output标志但将其值传递给output_folder参数,有点像这样:@click.option('--output', default='data', dest='output_folder')?点击有这种能力吗?我知道 argparse 允许这种行为。

4

1 回答 1

10

Yes, see the section in the click documentation on parameter names, which covers both options and arguments.

If a parameter is not given a name without dashes, a name is generated automatically by taking the longest argument and converting all dashes to underscores. For an option with ('-f', '--foo-bar'), the parameter name is foo_bar. For an option with ('-x',), the parameter is x. For an option with ('-f', '--filename', 'dest'), the parameter is called dest.

Here's your example:

from __future__ import print_function
import click

@click.command()
@click.option('--output', 'data')
def generate_data(data):
    print(data)

if __name__ == '__main__':
    generate_data()

Running it:

$ python2.7 stack_overflow.py --output some_output
some_output
于 2016-06-09T22:03:00.337 回答