Looks like a good use for a mutually exclusive group
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-d',
default='temp.file')
mx = parser.add_mutually_exclusive_group(required=True)
mx.add_argument('-g')
mx.add_argument('-s')
mx.add_argument('-m', nargs=2)
args = parser.parse_args()
print(args)
Sample runs:
1316:~/mypy$ python3 stack56926264.py -h
usage: stack56926264.py [-h] [-d D] (-g G | -s S | -m M M)
optional arguments:
-h, --help show this help message and exit
-d D
-g G
-s S
-m M M
1527:~/mypy$ python3 stack56926264.py -g foo
Namespace(d='temp.file', g='foo', m=None, s=None)
1528:~/mypy$ python3 stack56926264.py -s bar
Namespace(d='temp.file', g=None, m=None, s='bar')
1528:~/mypy$ python3 stack56926264.py -m 1 2
Namespace(d='temp.file', g=None, m=['1', '2'], s=None)
and catching some errors:
1528:~/mypy$ python3 stack56926264.py -m 1 2 -s bar -d afile
usage: stack56926264.py [-h] [-d D] (-g G | -s S | -m M M)
stack56926264.py: error: argument -s: not allowed with argument -m
1528:~/mypy$ python3 stack56926264.py -m 1
usage: stack56926264.py [-h] [-d D] (-g G | -s S | -m M M)
stack56926264.py: error: argument -m: expected 2 arguments
1530:~/mypy$ python3 stack56926264.py -d afile
usage: stack56926264.py [-h] [-d D] (-g G | -s S | -m M M)
stack56926264.py: error: one of the arguments -g -s -m is required