I have a python parsing arguments like below:
Code:
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Args test')
parser.add_argument('-myarg1', '--myarg1', type=str, dest='myarg1', required=True, help='Help yourself')
parser.add_argument('-myarg2', '--myarg2', type=str, dest='myarg2', default=' ', help='Help yourself')
args = parser.parse_args()
print(args.myarg1)
print(args.myarg2)
Above works if I call the script like below:
python myargs.py -myarg1 something -myarg2 somethingelse
But it does not work if I call it like below:
python myargs.py -myarg1 something -myarg2
And throws the below error obviously because it expects caller to pass value for the second argument.
usage: myargs.py [-h] -myarg1 MYARG1 [-myarg2 MYARG2]
myargs.py: error: argument -myarg2/--myarg2: expected one argument
Quesion:
I understand the reason for python complaining about it above. But, I want the user of my python script to be able to call the second argument with just saying -myarg2
or --myarg2
without specifying the type. Just like shell script style. Is it possible to do it with argparse
?
I am using python 2.7 and above.