I would like to have a program with subparsers that handles specific arguments while also keep some positional and optional arguments to the previous parsers (In fact what I really want is only one option, I mean, a valid subparser OR a valid local argument).
Example of something I wish to have: Program [{sectionName [{a,b}]}] [{c,d}]
. Being c/d incompatible if sectionName was provided and viceversa.
However, the best I could achieve is this test.py [-h] {sectionName} ... [{c,d}]
. This means, argparse don't allow me to use the positional arguments c or d without specifying a valid sectionName
.
Here is the code:
import argparse
mainparser = argparse.ArgumentParser()
# Subparser
subparser = mainparser.add_subparsers(title="section", required=False)
subparser_parser = subparser.add_parser("sectionName")
subparser_parser.add_argument("attribute", choices=['a', 'b'], nargs='?')
# Main parser positional and optional attributes
mainparser.add_argument("attribute", choices=['c', 'd'], nargs='?')
mainparser.parse_args()
I'm getting crazy with this. Any help would be much appreciated!
Edit: I'm using Python 3.8
The subparser
object is actually a positional Action
, one that takes choices
- in this case {'sectionName'}
. positinal
arguments are filled in the order that they are defined, using the nargs
pattern to allocate strings.
Once the main parser gets the 'sectionName' it passes the parsing to subparser_parser
. Than handles the rest of the input, such as the {'a','b'}
positional. Anything it can't handle is put on the 'unrecognized' list, and control returns main
for final processing. main
does not do any further argument processing. Thus your attribute
argument is ignored.
You could put define a attribute
positional before the add_subparsers
, but I wouldn't try to make it nargs='?'
.
So it's best to define all main
arguments before the subparsers, and to use optionals
. This will give the cleanest and most reliable parsing.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.