timchen
timchen

Reputation: 388

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.

Upvotes: 12

Views: 8924

Answers (2)

chepner
chepner

Reputation: 530990

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.

Upvotes: 14

Chris
Chris

Reputation: 17992

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")

Upvotes: 12

Related Questions