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

Community
  • 1
  • 1
Wang
  • 7,250
  • 4
  • 35
  • 66
  • New enough versions have a `required` parameter, https://stackoverflow.com/questions/23349349/argparse-with-required-subparser – hpaulj May 01 '19 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. – hpaulj May 01 '19 at 17:24

1 Answers1

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.

adrtam
  • 6,991
  • 2
  • 12
  • 27