AveryRe
AveryRe

Reputation: 23

Using Python3 and the argparse module, can I disallow an argument if a different one was passed?

For example, say the user passes an argument such as

python3 myscript.py -a

And I also want them to be able to pass

python3 myscript.py -b

But I don't want them to be able to pass both at the same time such as

python3 myscript.py -a -b

How would I go about doing this? I'm not too familiar with argparse as of yet and the documentation is kinda tough to comprehend.

Thanks a lot :)

Upvotes: 1

Views: 109

Answers (1)

Lev Levitsky
Lev Levitsky

Reputation: 65791

You want a mutually exclusive group of arguments. Here's a minimal example:

import argparse
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('-a', help='Do A', action='store_true')
group.add_argument('-b', help='Do B', action='store_true')
args = parser.parse_args()
if args.a:
    print('A!')
if args.b:
    print('B!')

Test:

$ python myscript.py -h
usage: myscript.py [-h] [-a | -b]

optional arguments:
  -h, --help  show this help message and exit
  -a          Do A
  -b          Do B
$ python myscript.py -a
A!
$ python myscript.py -b
B!
$ python myscript.py -a -b
usage: myscript.py [-h] [-a | -b]
myscript.py: error: argument -b: not allowed with argument -a

Upvotes: 2

Related Questions