Search code examples
pythonpython-click

Multiple words option


I'm currently trying to use multiple words options with click:

@click.command()
@click.option('--do-not-destroy', is_flag=True, default=False, 
              help='Do not destroy Selenium containers on exit')
@click.option('--run-tests', default=True, help="Run the tests.")
def main(do-not-destroy, run-tests):
    ...

Typically, I want to have an option that is called 'do-not-destroy'. Since the names of the parameters of the decorated function should be the name of the option, the parameter should be called 'do-not-destroy'.

Obviously, this parameter name is not valid.

Is there a way to tell click the name of the parameter it should use for an option (e.g. do_not_destroy)?


Solution

  • Click maps any options/arguments with dashes (-) to underscores (_). So:

    --do-not-destroy
    

    becomes:

    def main(do_not_destroy):
    

    Test Code:

    @click.command()
    @click.option('--opt-with-dashes')
    def hello(opt_with_dashes):
        """A Simple program"""
        click.echo('Opt w/ Dashes: {}'.format(opt_with_dashes))
    
    
    if __name__ == '__main__':
        hello('--opt-with-dashes OPTION'.split())
    

    Results:

    Opt w/ Dashes: OPTION