I've added a parameter -c, now I want to add another parameter called -ca. How can I set the default value of -ca as -c? What I want to do is if -ca is not specified, assign -c to -ca.
parser.add_argument("-c", type=str)
parser.add_argument("-ca", type=str, default=XXX)
You can set up your Python functions to have default values. Between the round brackets of your function definition, come up with a variable name then type an equals sign. After the equals sign, type a value for your variable. For example, suppose we want our function from the previous lesson to add ten to the answer.
After importing the library, argparse. ArgumentParser() initializes the parser so that you can start to add custom arguments. To add your arguments, use parser. add_argument() .
The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present. The source for this behavior is succinct and clear: http://hg.python.org/cpython/file/2.7/Lib/argparse.py#l861.
Metavar: It provides a different name for optional argument in help messages. Provide a value for the metavar keyword argument within add_argument() .
Normally, single dash flags are single characters. So -ca
is unwise, though not illegal. In normal POSIX practice it could be interpreted as -c a
or -c -a
.
Also argparse
allows flagged arguments (optionals
) to occur in any order.
Parsing starts out by assigning all the defaults. When the relevant flag is encountered, the new value overwrites the default. Given that order, it's impossible for one argument to take on the value of another as a default.
In general interactions between arguments are best handled after parsing. There is a mutually_exclusive
grouping, but no mutually_inclusive
. You can build in some sort of interaction via custom Action
classes, but implementing that is just as much work as any post-parsing testing.
In sum, the simplest thing is to use the default default
, None
, and test
if args.ca is None:
args.ca = args.c
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With