Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

argparse, two arguments depend on each other

I would like to make the parser like cmd [-a xxx -b xxx] -c xxx -d xxx

When -a is used, I want -b to be used too. likewise, if -b is used, -a must be used too. It's ok both -a and -b are not used.

How do I do that? I have tried custom actions, but it does not go well.

like image 796
timchen Avatar asked Jun 06 '13 16:06

timchen


People also ask

What does Argparse ArgumentParser () do?

>>> parser = argparse.ArgumentParser(description='Process some integers.') The ArgumentParser object will hold all the information necessary to parse the command line into Python data types.

What is action Store_true in Argparse?

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 does Nargs do in Argparse?

Using the nargs parameter in add_argument() , you can specify the number (or arbitrary number) of inputs the argument should expect. In this example named sum.py , the --value argument takes in 3 integers and will print the sum.

What is Subparser?

A “subparser” is an argument parser bound to a namespace. In other words, it works with everything after a certain positional argument. Argh implements commands by creating a subparser for every function.


2 Answers

A better design would be to have a single option that takes two arguments:

parser.add_argument('-a', nargs=2)

Then you either specify the option with 2 arguments, or you don't specify it at all.

$ script -a 1 2

or

$ script

A custom action (or postprocessing) can split the tuple args.a into two separate values args.a and args.b.

like image 82
chepner Avatar answered Sep 19 '22 17:09

chepner


Argparse doesn't natively support this type of use.

The most effective thing to do is check and see if those types of conditions are met after parsing:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-b')
parser.add_argument('-c')

args = parser.parse_args()

required_together = ('b','c')

# args.b will be None if b is not provided
if not all([getattr(args,x) for x in required_together]):
    raise RuntimeError("Cannot supply -c without -b")
like image 36
Chris Avatar answered Sep 19 '22 17:09

Chris