I need to implement a command line interface in which a program accepts subcommands.
For example, if the program is called "foo", the CLI will look like
foo cmd1 <cmd1-options>
foo cmd2
foo cmd3 <cmd3-options>
cmd1and cmd3must be used with at least one of their options, and the three arguments cmd*are always exceptional.
I am trying to use subparsers in argparse, but without success at the moment. The problem is cmd2that has no arguments:
if I try to add a subparser entry with no arguments, the namespace returned parse_argswill not contain any information telling me that this option is selected (see example below). if I try to add cmd2as an argument to parser(rather than a subparameter), then argparse expects that cmd2any of the subparameter arguments will follow the argument.
Is there an easy way to achieve this with argparse? Use case should be fairly common ...
What follows is what I tried to do so far, which is closer to what I need:
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='Functions')
parser_1 = subparsers.add_parser('cmd1', help='...')
parser_1.add_argument('cmd1_option1', type=str, help='...')
parser_2 = subparsers.add_parser(cmd2, help='...')
parser_3 = subparsers.add_parser('cmd3', help='...')
parser_3.add_argument('cmd3_options', type=int, help='...')
args = parser.parse_args()
source
share