Reputation: 475
My script needs to take exactly two arguments. The third one below is what I am struggling with.
python myscript -e arg1 arg2
python myscript -i arg1 arg2
python myscript arg1 arg2
I could easily get the first two to work using argparse
but I couldn't figure out how to get the third one to work with argparse. Basically, when no flag is specified, I would like to do same processing as with -e
flag specified. The script should error out if exactly 2 arguments haven't been specified.
I checked python documentation and saw that there is a way to specify a default value to a flag but I couldn't find a way to make the argument itself; a default one.
parser.add_argument('',nargs=2)
Although a newbie to python, I knew it was dumb to try the above thing, but somehow hoped that magically it would work. :)
Could someone help me find a way to get the no-argument case to work? Thanks
Upvotes: 4
Views: 1883
Reputation: 473873
Just add arg1
and arg2
required positional arguments:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-e', action='store_true')
parser.add_argument('-i', action='store_true')
parser.add_argument("arg1")
parser.add_argument("arg2")
args = parser.parse_args()
print(args)
Usage:
$ python test.py value1 value2 --help
usage: test.py [-h] [-e] [-i] arg1 arg2
positional arguments:
arg1
arg2
optional arguments:
-h, --help show this help message and exit
-e
-i
Upvotes: 3