简体   繁体   中英

How to pass in undefined parameters when use subparsers

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, the add_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, eg key=value . The key=value should 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 cd command or ls command

cd ~/Documents
#  ~/Documents is the positional argument
ls .
# . is the positional argument

Optional 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 curl program using the --config followed 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 --get which can be interpreted as get=True and tells the program to send get requests instead of the default post requests.

So if you are trying to use key=value it should look more like this. You can still specify nargs="*" then the parser will consider everything following the key= to be a single list argument with multiple space seperated items in it, or until it finds another valid argument.

parser.add_argument("--key", action='store', help="requires a value")

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM