0

I would like to make sure at least one of the sub commands is selected. But there is no required option for add_subparsers() how can I enforce at least one subparser is selected?

Currently I did this to mimic the effect:

subparsers = parser.add_subparsers( title='sub commands', help='valid sub commands', ) subparser1 = subparsers.add_parser('subcmd1') subparser1.set_defaults(which_subcmd='subcmd1') subparser2 = subparsers.add_parser('subcmd2') subparser2.set_defaults(which_subcmd='subcmd2') parsedargs = parser.parse_args() if 'which_subcmd' not in parsedargs: parser.print_help() 

But I want an official way to do this and make the help content display something like {subcmd1 | subcmd2}

Update:

according to @hpaulj, in 3.7 there is required option. But I want some work around can work in python 3.5 and 3.6

2
  • New enough versions have a required parameter, stackoverflow.com/questions/23349349/… Commented May 1, 2019 at 16:29
  • My old answer shows how to set the required attribute in older versions. Don't forget to set the dest as well. Commented May 1, 2019 at 17:24

1 Answer 1

0

Instead of printing help, I would prefer to raise an error:

if which_subcmd not in parsedargs: msg = "Subcommands needed: subcmd1, subcmd2" raise argparse.ArgumentTypeError(msg) 

This way is more consistent with other argparse errors. But just a matter of taste. I don't see anything wrong on your approach as long as you exit from your script after that print_help() statement.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.