python - How do I specify two required arguments, including a subcommand, using 'argparse'? -
is there way specify 2 required arguments in argparse
, 1 corresponds subcommand, , required subcommands.
the closest can manage seems with
import argparse parser = argparse.argumentparser() subparsers = parser.add_subparsers(help='', dest='command', metavar='command', title='required arguments', description='two arguments required') parser.add_argument('config', metavar='config', action='store', help='the config use') cmda_parser = subparsers.add_parser('cmda', help='a first command') cmdb_parser = subparsers.add_parser('cmdb', help='the second operation') cmdc_parser = subparsers.add_parser('cmdc', help='yet thing') print(parser.parse_args())
which gives
usage: enigma.py [-h] command ... config positional arguments: config config use optional arguments: -h, --help show message , exit required arguments: 2 arguments required command cmda first command cmdb second operation cmdc yet thing
and subcommands not show config
; want is
usage: enigma.py [-h] command config required arguments: 2 arguments required command cmda first command cmdb second operation cmdc yet thing config config use optional arguments: -h, --help show message , exit
and each subcommand show config
, eg.
usage: enigma.py cmda config [-h] required arguments: config config use optional arguments: -h, --help show message , exit
is there way accomplish this?
how specific two required arguments, 1 of subcommand, second "propagated" each subcommand required argument?
parsers can "inherit" arguments parser, using parents
attribute.
import argparse parser = argparse.argumentparser() # put common subparser arguments here. each sub parser have # own -h option, disable on shared base. subbase = argparse.argumentparser(add_help=false) subbase.add_argument('config', metavar='config', action='store', help='the config use') subparsers = parser.add_subparsers(help='', dest='command', metavar='command', title='required arguments', description='two arguments required') # add subbase parent list each subparser. cmda_parser = subparsers.add_parser('cmda', parents=[subbase], help='a first command') cmdb_parser = subparsers.add_parser('cmdb', parents=[subbase], help='the second operation') cmdc_parser = subparsers.add_parser('cmdc', parents=[subbase], help='yet thing') print(parser.parse_args())
Comments
Post a Comment