Search code examples
pythonpython-click

How to create both short and long options for one option in click (python package)?


How do I specify both a short option and long option for the same option? e.g., for the following, I also want to use -c for --count:

import click

@click.command()
@click.option('--count', default=1, help='count of something')
def my_command(count):
    click.echo('count=[%s]' % count)

if __name__ == '__main__':
    my_command()

e.g.,

$ python my_command.py --count=2
count=[2]
$ python my_command.py -c 3
count=[3]

References:
click documentation in a single pdf
click sourcecode on github
click website
click PyPI page


Solution

  • This is not well documented, but is quite straight forward:

    @click.option('--count', '-c', default=1, help='count of something')
    

    Test Code:

    @click.command()
    @click.option('--count', '-c', default=1, help='count of something')
    def my_command(count):
        click.echo('count=[%s]' % count)
    
    if __name__ == '__main__':
        my_command(['-c', '3'])
    

    Result:

    count=[3]