I'm attempting to convert my python from argparse to click. Using no_args_is_help I can get click to return the --help message even when the command line is empty. Whenever the help message is shown, the exit code that is passed to the system is still 0. Is there a way to change the exit code for the help message in the Click context or command call?
Below is example code that functions the way I want in all ways other than exit code. I could probably find a way to jerry-rig an exit change for when --help is called, but I can't see how to get under the hood enough to change the exit code for no_args_is_help.
import click
def hello(count, name):
"""Simple program that greets NAME for a total of COUNT times."""
for x in range(count):
click.echo(f"Hello {name}!")
@click.command(no_args_is_help=True)
@click.option('--count', default=1, help='Number of greetings.',show_default=True)
@click.option('--name',help='The person to greet.',required=True)
def manual_run(count,name):
hello(count,name)
if __name__ == '__main__':
manual_run()
Note, I would like the exit code to remain 0 for normal successful processing, and only change to 1 for a help-induced exit
I expected some kind of option along the lines of:
@click.command(no_args_is_help=True, help_exit_code=1)
but that doesn't work, and I can't find any documentation on editing the context of the help statement alone.
UPADTE:
It appears to work if you define a new command class with an overloaded get_help attribute:
class helpExit(click.Command):
def get_help(self, ctx):
helpstr=super().get_help(ctx)
click.echo(helpstr)
sys.exit(1)
and then pass that class in the command call:
@click.command(no_args_is_help=True,cls=helpExit)
Is this the best way to do this?