Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Argparse - Set default value of a parameter to another parameter

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)
like image 771
Allen Avatar asked Aug 15 '17 04:08

Allen


People also ask

How do I change the default value of a variable in Python?

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.

How do you pass arguments to Argparse?

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() .

What is Store_true in Python?

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.

What is Metavar in Argparse?

Metavar: It provides a different name for optional argument in help messages. Provide a value for the metavar keyword argument within add_argument() .


1 Answers

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
like image 125
hpaulj Avatar answered Sep 26 '22 01:09

hpaulj