Reputation: 64880
How would you construct a Python argparse parser to support different parameters organized by a top-level action, as well as have argparse's default help
functionality distinguish between the different action/option groups?
e.g.
$ myprog.py list --verbose
Listing records:
...
$ myprog.py run --iterations=10
Running
...
$ myprog.py help
usage: myprog.py [action]
positional arguments:
action {list,run,help}
list Lists records.
run Process records.
help Show action help.
$ myprog.py help run
usage: myprog.py run [--iterations=N] [--verbose] [--skip]
optional arguments:
--iterations N Process N records.
--verbose Show extra messaging.
--skip Skip previously seen IDs.
I thought this might be supported by the parents feature, but this seems more designed to grouping option groups than separate argument actions.
Upvotes: 0
Views: 141
Reputation: 24802
here's an example I made of using parsers and subparsers with argparse to achieve something close to what you're looking for, and that's a code to access SO by CLI ;-)
I'd also advise you to have a look at docopt
Upvotes: 1
Reputation: 231665
parents
is a convenient way of adding arguments to one or more parsers. It does not affect the parsing or the help.
add_argument_group
is a way of grouping arguments in the help
. It may be what you need. It does not, though, affect how the arguments are parsed. The default groupings are 'positional' and 'optional' (meaning 'uses a flag').
add_subparsers
is a way of both grouping arguments and their parsing. With it you create new parsers that are invoked with simple commands. Each subparser has its own set of arguments (and own help display)
If you want to organize the help
in an entirely different way, consider writing your own usage
and description
, and suppressing the default help lines with help=argparse.SUPPRESS
.
IPython
is an advanced user of argparse
. It detects help
in sys.argv
before calling argparse
, and thus bypasses the default help.
Upvotes: 0
Reputation: 1597
You could parse the first item, make your choice, then have different argument parsers for each item. If you want to share some commands, then you can use the parents feature to share some arguments between your various commands.
Upvotes: 0