268

Given:

import argparse

pa = argparse.ArgumentParser()
pa.add_argument('--foo')
pa.add_argument('--bar')

print pa.parse_args('--foo 1'.split())

how do I

  • make at least one of "foo, bar" mandatory: --foo x, --bar y and --foo x --bar y are fine
  • make at most one of "foo, bar" mandatory: --foo x or --bar y are fine, --foo x --bar y is not
Braiam
  • 1
  • 11
  • 47
  • 78
georg
  • 211,518
  • 52
  • 313
  • 390
  • 1
    possible duplicate of [How to code argparse combinational options in python](http://stackoverflow.com/questions/5603364/how-to-code-argparse-combinational-options-in-python) – robert Jun 22 '12 at 11:18

2 Answers2

432

I think you are searching for something like mutual exclusion (at least for the second part of your question).

This way, only foo or bar will be accepted, not both.

import argparse

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--foo',action=.....)
group.add_argument('--bar',action=.....)
args = parser.parse_args()

BTW, just found another question referring to the same kind of issue.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
jlengrand
  • 12,152
  • 14
  • 57
  • 87
  • 3
    @jlengrand your answer still worked for me after I realized it actually solves both conditions proposed in the question (`XOR`, basically). My initial concern was that yours only solved only one of the two conditions. – ijoseph Apr 13 '18 at 17:28
  • 1
    Thanks for the feedback. I had an idea it was solving everything indeed, but wasn't sure any more :D. I'll edit the answer accordingly! – jlengrand Apr 14 '18 at 08:48
  • This doesn't answer the first bullet point of the question, requiring one but allowing both – Dubslow May 04 '23 at 20:01
49

If you need some check that is not provided by the module you can always do it manually:

pa = argparse.ArgumentParser()
...
args = pa.parse_args()

if args.foo is None and args.bar is None:
   pa.error("at least one of --foo and --bar required")
sth
  • 222,467
  • 53
  • 283
  • 367
  • 1
    There's an [open issue](https://bugs.python.org/issue11588#msg226469) proposing to improve argparse to include different types of usage tested groups – artu-hnrq Oct 17 '21 at 07:52
  • alas! if only that open issue had gone anywhere... – Dubslow May 04 '23 at 20:00