When I use the subparsers, the subparers are optional parameters, and I have to choose one of them. Now, I want to implement the ability to pass in a default option when an option parameter that is not defined in the subparse is passed in, for example, theadd_codition.
parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('add_condition', nargs='*')
subparsers = parser.add_subparsers(help='sub-command help', dest="character")
subparsers.required = False
# create the parser for the "a" command
parser_a = subparsers.add_parser('a', help='a help')
parser_a.add_argument('--bar', choices='ABC', help='bar help')
# create the parser for the "b" command
parser_b = subparsers.add_parser('b', help='b help')
parser_b.add_argument('--baz', choices='XYZ', help='baz help')
However, when I pass in options that a subparser and b parser don't have, e.g. key=value. The key=valueshould theoretically be passed in add_codition.
The program result always prompts: error: argument character: invalid choice: 'key' (choose from 'a', 'b')
The python version is 3.6.9.
You are adding 'add-condition' as a positional argument. If you are trying to do a key=value type argument then you need to use an optional argument. Positional arguments don't take a key.
Some examples of positional arguments would be the path given to the
cdcommand orlscommandOptional arguments are the ones that can be structured as key value pairs, or they can be used as boolean flags. For example in cli for the
curlprogram using the--configfollowed by a filename points curl to use that specific filename as the config file. That is an example of the key value pair. Also in curl you can use the--getwhich can be interpreted asget=Trueand tells the program to send get requests instead of the default post requests.So if you are trying to use
key=valueit should look more like this. You can still specify nargs="*" then the parser will consider everything following thekey=to be a single list argument with multiple space seperated items in it, or until it finds another valid argument.