How to set the default option as -h for Python click?
By default, my script, shows nothing when no arguments is given to the duh.py
:
import click
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.command(context_settings=CONTEXT_SETTINGS)
@click.option('--toduhornot', is_flag=True, help='prints "duh..."')
def duh(toduhornot):
if toduhornot:
click.echo('duh...')
if __name__ == '__main__':
duh()
[out]:
$ python3 test_click.py -h
Usage: test_click.py [OPTIONS]
Options:
--toduhornot prints "duh..."
-h, --help Show this message and exit.
$ python3 test_click.py --toduhornot
duh...
$ python3 test_click.py
Question:
As shown above, the default prints no information python3 test_click.py
.
Is there a way such that, the default option is set to -h
if no arguments is given, e.g.
$ python3 test_click.py
Usage: test_click.py [OPTIONS]
Options:
--toduhornot prints "duh..."
-h, --help Show this message and exit.
If you inherit from
click.Command
and override theparse_args()
method, you can create a custom class to default to help like:Custom Class
Using Custom Class:
To use the custom class, pass the
cls
parameter to@click.command()
decorator like:How does this work?
This works because click is a well designed OO framework. The
@click.command()
decorator usually instantiates aclick.Command
object but allows this behavior to be over ridden with thecls
parameter. So it is a relatively easy matter to inherit fromclick.Command
in our own class and over ride the desired methods.In this case we over-ride
click.Command.parse_args()
and check for an empty argument list. If it is empty then we invoke the help. In addition this class will default the help to['-h', '--help']
if it is not otherwise set.Test Code:
Results:
Your structure is not the recommended one, you should use:
And then
python test_click.py
will print help message:So you can use
python test_click.py duh
to callduh
.Update
Easiest approach I've found