My program uses Click for command line processing. It has a main command that takes a required argument. This command has subcommands that take optional arguments. Different subcommands take different options, but they all require the same argument from their parent. I'd like to have the command line look like this:
python myprogram.py argument-value subcommand1 --option-1=value
I can write this using Click like so
import click
@click.group()
@click.argument("argument")
@click.pass_context
def main(context, argument):
"""ARGUMENT is required for both subcommands"""
context.obj = {"argument": argument}
@click.command()
@click.option("--option-1", help="option for subcommand 1")
@click.pass_context
def subcommand1(context, option_1):
print("subcommand 1: %s %s" % (context.obj["argument"], option_1))
@click.command()
@click.option("--option-2", help="option for subcommand 2")
@click.pass_context
def subcommand2(context, option_2):
print("subcommand 2: %s %s" % (context.obj["argument"], option_2))
main.add_command(subcommand1)
main.add_command(subcommand2)
if __name__ == "__main__":
main()
The top-level help message is what I want.
python myprogram.py --help
Usage: myprogram.py [OPTIONS] ARGUMENT COMMAND [ARGS]...
ARGUMENT is required for both subcommands
Options:
--help Show this message and exit.
Commands:
subcommand1
subcommand2
I can get help for a subcommand if I pass in the required argument.
python myprogram.py dummy-argument subcommand1 --help
Usage: myprogram.py subcommand1 [OPTIONS]
Options:
--option-1 TEXT option for subcommand 1
--help Show this message and exit.
However, I'd like to get the subcommand help without requiring the user to pass in a dummy argument. I want to be able to run python myprogram.py subcommand1 --help
and see the same output as above, but instead I just get the help text for the top level.
python myprogram.py subcommand1 --help
Usage: myprogram.py [OPTIONS] ARGUMENT COMMAND [ARGS]...
ARGUMENT is required for both subcommands
Options:
--help Show this message and exit.
Commands:
subcommand1
subcommand2
Is there a way to get the behavior I want? I realize that Click puts a premium on having each of its commands be self-contained, but this seems like a common scenario.
argument
to be the same as thesubcommand
, or are these name spaces unique? – Zerlineargparse
that is built-in. – Epidote